Requests
发送 HTTP 请求,常用于调用接口和下载文件。本页示例使用公开的 httpbin 测试服务,需要联网。
安装与导入
python -m pip install requests
import requests
各小节共用导入;示例中的文件保存到运行脚本的当前目录。
常用用法
GET 请求与查询参数
response = requests.get(
"https://httpbin.org/get",
params={"q": "python", "page": 1},
timeout=(3.05, 10),
)
response.raise_for_status()
data = response.json()
print(data["args"])
params 拼接查询字符串;timeout 元组依次指定连接和读取等待时间,见快速开始。
POST:JSON 与表单
response = requests.post(
"https://httpbin.org/post",
json={"name": "Rovaire", "topic": "python"},
timeout=(3.05, 10),
)
response.raise_for_status()
print(response.json()["json"])
接口要 JSON 时用 json=;普通表单用 data={...};上传文件用 files=。不要把 JSON 字符串误当成普通表单字段。
读取不同类型的响应
| 属性或方法 | 用途 |
|---|---|
response.status_code | 状态码 |
response.headers | 响应头 |
response.text | 解码后的文本 |
response.content | 原始字节,适合二进制文件 |
response.json() | 将响应体解析为 Python 数据 |
json() 解析成功不代表 HTTP 状态成功,通常先调用 raise_for_status()。
Session:复用连接和公共配置
with requests.Session() as session:
session.headers.update({"User-Agent": "Rovaire-Notebook/1.0"})
response = session.get("https://httpbin.org/headers", timeout=(3.05, 10))
response.raise_for_status()
print(response.json()["headers"])
Session 还能保存 Cookie;公共超时需要自己封装,不能假定所有请求会继承某个随手设置的属性。见Session 用法。
错误处理
try:
response = requests.get("https://httpbin.org/get", timeout=(3.05, 10))
response.raise_for_status()
print(response.json())
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.HTTPError as exc:
print("HTTP 错误:", exc.response.status_code)
except requests.exceptions.RequestException as exc:
print("请求或响应处理失败:", exc)
进阶与不常用用法
为可重试的读取请求配置重试
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
retry = Retry(
total=3, backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods={"GET", "HEAD"},
)
with requests.Session() as session:
session.mount("https://", HTTPAdapter(max_retries=retry))
response = session.get("https://httpbin.org/get", timeout=(3.05, 10))
response.raise_for_status()
这里对指定读取方法的临时错误重试。POST 是否适合重试取决于接口的幂等性;参数含义见 Retry。
流式下载,避免一次性读入内存
with requests.get(
"https://httpbin.org/bytes/1024", stream=True, timeout=(3.05, 10),
) as response:
response.raise_for_status()
with open("download.bin", "wb") as file:
for chunk in response.iter_content(chunk_size=64 * 1024):
if chunk:
file.write(chunk)
上下文会关闭响应。大文件不要再读取 response.content,否则会失去分块读取的意义,见流式响应。
易错点
- Requests 默认没有请求超时,实际调用应显式设置
timeout。 - 读取超时限制的是等待数据的时间,不是整个下载的总时长。
.text用于文本,图片等二进制内容使用.content或流式读取。- Requests 是同步库;大量并发请求要另行设计并发方式。