1. requests 是什么? #

2. 安装 requests #

# 用 pip 安装 requests 库
pip install requests
# 导入并打印版本号,验证安装成功
python -c "import requests; print(requests.__version__)"

3. 前置知识:HTTP 基础 #

4. GET 请求 #

# 导入 requests 库
import requests

# 发送基础 GET 请求
response = requests.get('https://httpbin.org/get')
# 打印 HTTP 状态码
print(f"状态码: {response.status_code}")
# 打印响应正文前 200 个字符
print(response.text[:200])

# 定义查询参数字典
params = {'name': '张三', 'page': 1}
# 发送带 params 的 GET 请求
response = requests.get('https://httpbin.org/get', params=params)
# 打印实际请求的完整 URL
print(f"URL: {response.url}")

5. 设置请求头 #

# 导入 requests 库
import requests

# 定义自定义请求头
headers = {
    'User-Agent': 'MyApp/1.0',
    'Accept': 'application/json',
}
# 发送带请求头的 GET 请求
response = requests.get('https://httpbin.org/headers', headers=headers)
# 打印服务器收到的请求头
print(response.text)

6. POST 请求(JSON) #

# 导入 requests 库
import requests

# 定义要提交的 JSON 数据
payload = {'name': '张三', 'age': 25}
# 发送 POST 请求,json= 自动序列化并设置 Content-Type
response = requests.post('https://httpbin.org/post', json=payload)
# 打印状态码
print(f"状态码: {response.status_code}")
# 打印服务器返回的响应
print(response.text)

7. 处理响应 #

# 导入 requests 库
import requests

# 请求公开测试 API 获取用户信息
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
# 将 JSON 响应解析为字典
user = response.json()
# 打印用户姓名和邮箱
print(f"姓名: {user['name']}, 邮箱: {user['email']}")

# 请求一张测试 PNG 图片
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. 超时与异常处理 #

# 导入 requests 库
import requests
# 导入常用异常类型
from requests.exceptions import Timeout, ConnectionError, HTTPError

try:
    # 发送 GET 请求,最多等待 10 秒
    response = requests.get('https://httpbin.org/get', timeout=10)
    # 状态码非 2xx 时抛出 HTTPError
    response.raise_for_status()
    # 解析 JSON 并打印请求 URL
    print("成功:", response.json().get('url'))
except Timeout:
    # 超过 timeout 未收到响应
    print("请求超时")
except ConnectionError:
    # DNS 失败、断网等连接问题
    print("网络连接失败")
except HTTPError as e:
    # 4xx/5xx 状态码错误
    print(f"HTTP 错误: {e.response.status_code}")

9. Session:保持登录态 #

# 导入 requests 库
import requests

# 创建 Session,退出 with 时自动关闭连接
with requests.Session() as session:
    # 设置会话级默认请求头
    session.headers.update({'User-Agent': 'MyApp/1.0'})
    # 第一次请求:服务器设置 Cookie
    session.get('https://httpbin.org/cookies/set?session_id=abc123')
    # 第二次请求:自动携带 Cookie
    response = session.get('https://httpbin.org/cookies')
    # 打印服务器收到的 Cookie
    print(response.text)

10. 常见错误 #

错误现象 解决办法
ModuleNotFoundError pip install requests
一直卡住 加 timeout=10
服务器收不到 JSON POST 改用 json=payload
JSONDecodeError 先 raise_for_status() 再 json()

11. requests 与 urllib #

特性 requests urllib
安装 pip install 内置
GET requests.get(url) urlopen + decode
POST JSON json=payload 手动编码
易用性 高 较低

12. 总结 #

12.1 速查 #

# 导入 requests 库
import requests

# GET 请求:带查询参数和超时
response = requests.get(url, params={'k': 'v'}, timeout=10)
# POST 请求:提交 JSON 数据
response = requests.post(url, json={'name': '张三'}, timeout=10)
# 检查状态码,非 2xx 抛异常
response.raise_for_status()
# 解析 JSON 响应为 Python 对象
data = response.json()

12.2 最佳实践 #