什么是 requests 库?
requests 库是一个用 Python 编写的、基于 urllib3 的第三方库,它提供了简单易用的 API,让你能够轻松地发送 HTTP/1.1 请求,并自动处理很多底层的细节,

- 会话管理
- Cookie 持久化解码
- 文件上传
- 连接池
- 超时设置
安装: 在使用之前,你需要先安装它。
pip install requests
核心功能与常用方法
requests 的核心是 requests 模块,你通常这样导入它:
import requests
发送请求
requests 为所有常见的 HTTP 方法都提供了对应的函数,它们都返回一个 Response 对象。
| 方法 | 描述 |
|---|---|
requests.get(url) |
发送一个 GET 请求,用于获取数据。 |
requests.post(url, data=None, json=None) |
发送一个 POST 请求,通常用于提交数据。 |
requests.put(url, data=None) |
发送一个 PUT 请求,用于更新数据。 |
requests.delete(url) |
发送一个 DELETE 请求,用于删除数据。 |
requests.head(url) |
发送一个 HEAD 请求,类似于 GET,但只响应头。 |
requests.options(url) |
发送一个 OPTIONS 请求,用于获取服务器支持的 HTTP 方法。 |
Response 对象
当你发送一个请求后,requests 会返回一个 Response 对象,这个对象包含了服务器对请求的所有响应信息。

response = requests.get('https://www.example.com')
Response 对象的常用属性:
| 属性 | 描述 |
|---|---|
response.status_code |
HTTP 状态码,200 (成功), 404 (未找到), 500 (服务器错误)。 |
response.text |
的字符串形式。requests 会自动根据 headers 中的 Content-Type 和 charset 来解码。 |
response.content |
的字节形式,适合处理非文本数据,如图片、文件等。 |
response.json() |
如果响应内容是 JSON 格式,这个方法会将其解析为 Python 字典,如果解析失败会抛出 JSONDecodeError。 |
response.headers |
一个类似字典的对象,包含了响应头信息。 |
response.url |
最终请求的 URL(可能会因为重定向而改变)。 |
response.history |
一个包含所有重定向请求的 Response 对象的列表。 |
response.cookies |
一个 RequestsCookieJar 对象,包含了从服务器返回的 Cookie。 |
实战示例
示例 1:简单的 GET 请求
import requests
# 1. 发送 GET 请求
url = 'https://api.github.com'
response = requests.get(url)
# 2. 检查请求是否成功 (状态码 200)
if response.status_code == 200:
# 3. 获取并打印响应内容
# response.text 是字符串格式
print("响应内容 (text):")
print(response.text[:200] + "...") # 只打印前200个字符
# response.json() 会自动解析为字典
print("\n响应内容 (json):")
data = response.json()
print(f"API 名称: {data.get('current_user_url')}")
else:
print(f"请求失败,状态码: {response.status_code}")
示例 2:带参数的 GET 请求 (查询参数)
当你需要向 URL 添加查询参数(如 ?key1=value1&key2=value2)时,可以直接在 URL 中拼接,但 requests 提供了更优雅的方式:params 参数。
import requests
# 目标URL基础部分
base_url = 'https://httpbin.org/get'
# 查询参数
params = {
'name': 'John Doe',
'age': 30,
'city': 'New York'
}
# 发送带参数的GET请求
response = requests.get(base_url, params=params)
# 检查响应
if response.status_code == 200:
# httpbin.org 会返回你发送的请求信息
# 我们可以看到 'args' 部分包含了我们传递的参数
data = response.json()
print("服务器收到的查询参数:")
print(data['args'])
示例 3:POST 请求(发送表单数据)
POST 请求通常用于提交数据。data 参数用于发送表单格式的数据(application/x-www-form-urlencoded)。
import requests
url = 'https://httpbin.org/post'
# 要提交的表单数据
payload = {
'username': 'testuser',
'password': 'securepassword123'
}
# 发送 POST 请求
response = requests.post(url, data=payload)
if response.status_code == 200:
data = response.json()
print("服务器收到的表单数据:")
print(data['form'])
示例 4:POST 请求(发送 JSON 数据)
当与 RESTful API 交互时,通常需要发送 JSON 格式的数据,这时应使用 json 参数。

import requests
import json # 虽然requests会自动处理,但有时需要用到json模块
url = 'https://httpbin.org/post'
# 要发送的JSON数据
json_payload = {
'name': 'Jane Doe',
'is_student': False,
'courses': ['History', 'Math']
}
# 发送 JSON 数据,requests会自动设置 Content-Type 为 application/json
response = requests.post(url, json=json_payload)
if response.status_code == 200:
data = response.json()
print("服务器收到的JSON数据:")
print(data['json'])
示例 5:自定义请求头
有些网站需要特定的请求头才能正常访问,例如设置 User-Agent 来模拟浏览器访问。
import requests
url = 'https://httpbin.org/get'
# 自定义请求头
headers = {
'User-Agent': 'My Cool App 1.0',
'Accept-Language': 'en-US,en;q=0.9'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print("服务器收到的请求头:")
print(data['headers'])
示例 6:处理响应超时
为了避免程序因服务器无响应而长时间挂起,可以设置超时时间。
import requests
try:
# 设置超时时间为 5 秒
# timeout 可以是一个元组 (connect_timeout, read_timeout)
response = requests.get('https://httpbin.org/delay/10', timeout=5)
print("请求成功!")
except requests.exceptions.Timeout:
print("请求超时!")
except requests.exceptions.RequestException as e:
print(f"发生请求错误: {e}")
高级主题
会话对象 (Session)
Session 对象可以在多个请求之间保持某些参数,如 Cookie,当你需要向同一主机发送多个请求时,使用 Session 会更高效,因为它会重用底层 TCP 连接。
import requests
# 1. 创建一个 Session 对象
with requests.Session() as session:
# 2. 在会话中设置通用参数,如 headers
session.headers.update({'User-Agent': 'MyApp/1.0'})
# 3. 第一次请求,可能会收到并保存 Cookie
response1 = session.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
print("第一次请求后的 Cookie:", response1.cookies.get_dict())
# 4. 第二次请求到同一个域名,会自动带上之前的 Cookie
response2 = session.get('http://httpbin.org/cookies')
print("第二次请求结果:", response2.json())
身份验证
requests 内置了对基本 HTTP 身份验证(Basic Auth)的支持。
from requests.auth import HTTPBasicAuth
url = 'https://httpbin.org/basic-auth/user/passwd'
# 用户名: user, 密码: passwd
# 方式一:使用 auth 参数
response = requests.get(url, auth=HTTPBasicAuth('user', 'passwd'))
# 方式二:使用元组 (更简洁)
response = requests.get(url, auth=('user', 'passwd'))
print(response.status_code) # 成功时为 200
print(response.json()) # 会返回 {'authenticated': True, 'user': 'user'}
代理
如果你的网络需要通过代理服务器访问,可以这样设置:
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('https://example.com', proxies=proxies)
requests 库是 Python 开发者进行网络请求的必备工具,它的核心优势在于简洁和人性化。
核心要点回顾:
- 安装:
pip install requests - 发送请求:
requests.get(),requests.post()等。 - 响应处理:通过返回的
Response对象获取status_code,text,content,json()等。 - 传递参数:使用
params传递查询参数,data传递表单数据,json传递 JSON 数据。 - 定制请求:通过
headers和auth等参数定制请求。 - 会话管理:使用
Session对象来保持连接和 Cookie。 - 错误处理:总是检查
status_code或使用try...except捕获requests.exceptions下的异常。
掌握 requests 库,你就可以轻松地与任何 Web API 交互,爬取网页数据,构建各种网络应用。
