下面是一份2026年最新视角的 Python requests 模块全面学习教程,适合零基础到中级开发者。
内容基于 requests 2.32.5(2025年8月最新稳定版,支持 Python 3.9+,已放弃 Python 3.8)。
目标:学完后能熟练处理 95% 的 HTTP 场景,包括爬虫、API 调用、文件上传、认证、超时、重试、会话保持等。
1. 安装与快速验证
pip install requests # 推荐(最新版)
# 或指定版本(生产环境常用)
pip install requests==2.32.5
验证(交互式或脚本):
import requests
print(requests.__version__) # 应该看到 2.32.x
r = requests.get("https://httpbin.org/get")
print(r.status_code) # 200
print(r.json()["url"]) # https://httpbin.org/get
2. 核心方法一览(最常用 7 个)
| 方法 | 用途 | 常见场景 | 返回值类型 |
|---|---|---|---|
| get() | 获取资源 | 查询参数、爬取页面、调用 GET API | Response |
| post() | 提交数据(创建) | 登录、表单提交、JSON API | Response |
| put() | 更新/替换资源 | 更新用户资料、全量替换 | Response |
| patch() | 部分更新 | 只改某个字段 | Response |
| delete() | 删除资源 | 删除文章、注销账号 | Response |
| head() | 只获取响应头 | 检查资源是否存在、大小、修改时间 | Response |
| options() | 查询服务器支持的方法 | CORS 预检(较少用) | Response |
3. 基本使用模板(强烈推荐每次都这样写)
import requests
from requests.exceptions import RequestException
try:
response = requests.get(
"https://api.example.com/users",
params={"page": 1, "limit": 20}, # 查询参数
headers={"User-Agent": "MyApp/1.0"},
timeout=10, # 必加!
)
response.raise_for_status() # 非 2xx 抛异常
data = response.json() # 自动解析 JSON
print(data)
except requests.Timeout:
print("请求超时")
except requests.ConnectionError:
print("网络连接失败")
except RequestException as e:
print(f"请求异常: {e}")
4. 核心属性与方法(Response 对象)
| 属性/方法 | 说明 | 示例用法 |
|---|---|---|
| status_code | 状态码 | 200, 404, 500 等 |
| ok | True 如果 status_code < 400 | if not r.ok: … |
| reason | 状态描述(如 “OK”, “Not Found”) | |
| text | 响应体(unicode 字符串) | r.text.strip() |
| content | 响应体(bytes) | 保存图片/文件用 |
| json() | 解析 JSON(失败抛 JSONDecodeError) | data = r.json() |
| headers | 响应头(CaseInsensitiveDict) | r.headers[“Content-Type”] |
| cookies | 响应中的 cookies | r.cookies[“sessionid”] |
| encoding | 编码(可手动设置) | r.encoding = “utf-8” |
| raise_for_status() | 非 2xx 抛 HTTPError | 推荐在 response 后立即调用 |
| iter_content() | 流式读取(大文件) | 下载大文件时用 |
5. 传递参数的 4 种常见方式
# 1. 查询参数(GET 最常用)
requests.get("https://httpbin.org/get", params={"q": "python", "page": 2})
# 2. 表单数据(application/x-www-form-urlencoded)
requests.post("https://httpbin.org/post", data={"username": "admin", "password": "123"})
# 3. JSON 数据(Content-Type: application/json)
requests.post("https://httpbin.org/post", json={"name": "Alice", "age": 28})
# 4. 文件上传(multipart/form-data)
files = {"file": open("report.pdf", "rb")}
requests.post("https://httpbin.org/post", files=files)
6. Headers 与 Cookies 处理
# 自定义 headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120",
"Authorization": "Bearer your_token_here",
"Accept-Language": "zh-CN,zh;q=0.9",
}
r = requests.get(url, headers=headers)
# 自动管理 cookies(会话内保持)
session = requests.Session()
session.get("https://example.com/login", data=login_data)
r = session.get("https://example.com/profile") # 自动带上登录后的 cookie
7. 超时、重试、代理(生产必备)
# 推荐超时写法(连接超时 + 读取超时)
requests.get(url, timeout=(3.05, 27)) # 连接 3s,读取 27s
# 简单重试(推荐用 requests.adapters + urllib3)
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("https://", HTTPAdapter(max_retries=retries))
session.mount("http://", HTTPAdapter(max_retries=retries))
# 代理(支持 http/https/socks5)
proxies = {
"http": "http://user:pass@proxy_ip:port",
"https": "http://user:pass@proxy_ip:port",
# "all": "socks5://127.0.0.1:1080" # 需要 pip install requests[socks]
}
requests.get(url, proxies=proxies)
8. 会话(Session) — 性能与状态保持的关键
session = requests.Session()
session.headers.update({"User-Agent": "MyBot/1.0"})
session.auth = ("user", "pass") # 基础认证
session.cookies.set("theme", "dark")
# 连接池复用、cookie 自动保持、统一 headers/auth
for url in url_list:
response = session.get(url)
9. 认证方式汇总
| 类型 | 代码示例 | 场景 |
|---|---|---|
| Basic Auth | auth=("user", "pass") | 内网、旧系统 |
| Digest Auth | from requests.auth import HTTPDigestAuth | 少数 API |
| Bearer Token | headers={"Authorization": f"Bearer {token}"} | JWT/OAuth2 最常见 |
| API Key | params={"api_key": KEY} 或 headers | OpenAI、天气 API 等 |
| OAuth 1/2 | 用 requests-oauthlib | Twitter/X、部分企业 |
10. 流式请求与大文件下载
# 流式下载(内存友好)
r = requests.get("https://example.com/bigfile.zip", stream=True)
with open("bigfile.zip", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
11. 常见异常处理全家桶
from requests.exceptions import (
Timeout, ConnectionError, HTTPError,
TooManyRedirects, RequestException
)
try:
r = requests.get(url, timeout=8)
r.raise_for_status()
except Timeout:
# 重试或切换代理
except ConnectionError:
# 网络问题
except HTTPError as e:
print(f"HTTP 错误: {e.response.status_code}")
except TooManyRedirects:
# 无限重定向
except RequestException as e:
# 兜底
12. 进阶推荐方向(学完基础后选修)
- 异步 HTTP:httpx(支持 async/await,API 与 requests 几乎相同)
- 浏览器行为模拟:requests + fake-useragent + cloudscraper(防反爬)
- 重试/限流/熔断:tenacity + requests
- 结构化日志:structlog + requests 的钩子
- mock 测试:responses 或 httpx 的 mock
快速自测清单(学完后能独立完成)
- 调用带 token 的 GET API 并解析 JSON
- POST JSON 数据并处理 4xx/5xx
- 上传单个/多个文件
- 用 Session 保持登录状态爬取多页
- 下载大文件不爆内存
- 设置超时 + 自动重试 3 次
- 处理代理 + 自定义 UA
如果你能全部实现,恭喜你 requests 已经入门到熟练!
有具体场景想深入(比如反爬、模拟登录、并发下载、结合 pandas 批量调用 API)?告诉我,我给你针对性代码 + 注意事项。加油~