1. requests 是什么? #
requests 是 Python 最流行的第三方 HTTP 库,几行代码即可发送请求、调用 API。
- 相比标准库
urllib,语法更简洁:requests.get(url) 一行搞定。
- 需要先
pip install requests 安装,建议在虚拟环境中使用。
- 适合调用 REST API、爬取数据、下载文件等日常场景,是项目网络请求的首选。
2. 安装 requests #
requests 不是 Python 内置库,需用 pip 单独安装。
- 安装后执行
python -c "import requests; print(requests.__version__)" 验证。
- 国内网络慢时可加清华镜像加速安装。
pip install requests
python -c "import requests; print(requests.__version__)"
3. 前置知识:HTTP 基础 #
- GET 从服务器获取数据;POST 向服务器提交数据(如调用 API、创建资源)。
- 常见状态码:
200 成功、404 不存在、500 服务器错误。
- URL 示例:
https://api.example.com/users?page=1 = 协议 + 域名 + 路径 + 查询参数。
- 下文示例使用 httpbin.org 和 jsonplaceholder,无需注册即可运行。
4. GET 请求 #
requests.get(url) 发送 GET 请求,返回 Response 对象。
response.status_code 是状态码,response.text 是响应正文字符串。
- 查询参数用
params 字典传递,requests 自动拼接到 URL 并编码中文。
import requests
response = requests.get('https://httpbin.org/get')
print(f"状态码: {response.status_code}")
print(response.text[:200])
params = {'name': '张三', 'page': 1}
response = requests.get('https://httpbin.org/get', params=params)
print(f"URL: {response.url}")
5. 设置请求头 #
- 请求头(headers)传递客户端类型、数据格式、认证信息等附加信息。
User-Agent 标识程序身份,脚本请求时建议设置,避免被网站拦截。
Authorization: Bearer <token> 是 API 认证最常用的方式。
import requests
headers = {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json',
}
response = requests.get('https://httpbin.org/headers', headers=headers)
print(response.text)
6. POST 请求(JSON) #
- 现代 API 普遍用 JSON 传参,用
json= 参数即可,自动序列化并设置 Content-Type。
- 传 JSON 用
json=,传表单用 data=,两者不要混用。
data= 用于传统表单提交(application/x-www-form-urlencoded),新手调用 API 几乎只用 json=。
import requests
payload = {'name': '张三', 'age': 25}
response = requests.post('https://httpbin.org/post', json=payload)
print(f"状态码: {response.status_code}")
print(response.text)
7. 处理响应 #
- API 返回 JSON 时用
response.json() 解析为字典或列表,最常用。
response.text 适合文本;response.content 是字节,适合下载图片、文件。
- 下载文件:
response.content 配合 open(path, 'wb') 写入本地。
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
user = response.json()
print(f"姓名: {user['name']}, 邮箱: {user['email']}")
response = requests.get('https://httpbin.org/image/png', timeout=10)
response.raise_for_status()
with open('downloaded.png', 'wb') as f:
f.write(response.content)
print("已保存 downloaded.png")
8. 超时与异常处理 #
- 务必设置
timeout,否则网络异常时程序可能无限等待。
response.raise_for_status() 在 4xx/5xx 时抛 HTTPError,应在读 json() 前调用。
- 用
try/except 分别捕获超时、连接失败、HTTP 错误。
import requests
from requests.exceptions import Timeout, ConnectionError, HTTPError
try:
response = requests.get('https://httpbin.org/get', timeout=10)
response.raise_for_status()
print("成功:", response.json().get('url'))
except Timeout:
print("请求超时")
except ConnectionError:
print("网络连接失败")
except HTTPError as e:
print(f"HTTP 错误: {e.response.status_code}")
9. Session:保持登录态 #
requests.Session() 在多次请求间保持 Cookie、复用连接,适合需要登录的场景。
- 单次请求直接用
requests.get() 即可;需要登录态时用 with requests.Session() as session:。
- 会话级
headers 设置一次,后续请求自动携带。
import requests
with requests.Session() as session:
session.headers.update({'User-Agent': 'MyApp/1.0'})
session.get('https://httpbin.org/cookies/set?session_id=abc123')
response = session.get('https://httpbin.org/cookies')
print(response.text)
10. 常见错误 #
- 忘记
timeout 导致程序卡住,始终加 timeout=10。
- POST 传 JSON 误用
data=,应改用 json=。
- 不检查状态码,
404 不会自动抛异常,用 raise_for_status()。
- 未安装 requests 会报
ModuleNotFoundError,先执行 pip install requests。
| 错误现象 |
解决办法 |
ModuleNotFoundError |
pip install requests |
| 一直卡住 |
加 timeout=10 |
| 服务器收不到 JSON |
POST 改用 json=payload |
JSONDecodeError |
先 raise_for_status() 再 json() |
11. requests 与 urllib #
requests 语法简单,日常开发首选;urllib 是标准库,零依赖。
- 不能装第三方包时用
urllib(见 15.urllib.md);批量并发见 14.concurrent.md。
| 特性 |
requests |
urllib |
| 安装 |
pip install |
内置 |
| GET |
requests.get(url) |
urlopen + decode |
| POST JSON |
json=payload |
手动编码 |
| 易用性 |
高 |
较低 |
12. 总结 #
- 核心流程:安装 →
get/post → json() 读响应 → timeout + raise_for_status() + 异常处理。
- 记住:
params 查参、json 传体、headers 设头、登录用 Session。
- 示例均可独立运行,复制为
.py 文件即可测试。
12.1 速查 #
import requests
response = requests.get(url, params={'k': 'v'}, timeout=10)
response = requests.post(url, json={'name': '张三'}, timeout=10)
response.raise_for_status()
data = response.json()
12.2 最佳实践 #
- 始终设置
timeout
- POST JSON 用
json=,不用 data=
raise_for_status() + try/except 处理失败
- 需要登录态用
Session
- 在虚拟环境中安装,见
1.pip.md、2.venv.md