Python使用requests库发起HTTP请求的完整指南
本文详细介绍如何使用 Python 第三方库 requests 快速发起各类 HTTP 请求。内容涵盖 GET/POST 请求的标准写法、动态参数传递、自定义请求头与 Cookie 设置、Session 会话保持机制以及完善的异常分类处理方案。附带可直接运行的代码示例与调试技巧,帮助开发者高效完成后端接口调试与自动化脚本编写。
环境准备与依赖安装
使用前请确保 Python 环境已就绪。requests 为非内置库,需通过包管理器安装:
> pip install requests
核心操作流程
第1步:发起基础 GET 请求
目的:向服务器请求单一资源并获取返回数据。适用于查阅接口文档或提取公开信息。
入口:调用 requests.get() 并传入目标 URL。
import requests
# 使用官方测试 API 模拟数据
resp = requests.get("http://jsonplaceholder.typicode.com/posts/3")
if resp.status_code == 200:
# 直接解析 JSON 响应体
data = resp.json()
print(data)
else:
print(f"请求失败,状态码:{resp.status_code}")
第2步:携带参数进行条件查询
目的:在 URL 末尾拼接查询字符串(Query String),用于过滤或分页数据。无需手动拼接字符串,库会自动编码特殊字符。
入口:在 requests.get() 中添加 params 字典参数。
import requests
param = {
"userId": 2
}
resp = requests.get("http://jsonplaceholder.typicode.com/posts", params=param)
if resp.status_code == 200:
data = resp.json()
print(data)
else:
print(f"请求失败,状态码:{resp.status_code}")
第3步:发送 POST 请求并配置 Headers
目的:向服务器提交结构化数据。多数现代 API 接收 JSON 格式负载,需显式设置 Content-Type 并序列化字典。
入口:requests.post(),搭配 data(需序列化)与 headers 参数。
import requests
import json
data = {
"userId": 11,
"title": "requests post demo",
"body": "requests post body"
}
# 注意:Content-Type 应使用标准 application/json
headers = {'Content-Type': 'application/json'}
resp = requests.post(
"http://jsonplaceholder.typicode.com/posts",
data=json.dumps(data),
headers=headers
)
if resp.status_code in (200, 201):
data = resp.json()
print(data)
else:
print(f"请求失败,状态码:{resp.status_code}")
第4步:维护 Cookies 与会话状态
目的:跨请求保持登录态或追踪业务标识。单次请求默认不共享 Cookie,需借助 requests.Session 对象实现状态持久化。
入口:requests.Session() 实例化后,连续调用其封装的请求方法即可自动透传 Cookie。
import requests
# 手动附带初始 Cookie(可选场景)
cookies = {'session_id': '12345', 'user_token': 'abcdef'}
resp = requests.get("http://jsonplaceholder.typicode.com/posts/1", cookies=cookies)
# 创建会话对象保持上下文
session = requests.Session()
response = session.get('https://example.com/login')
response = session.get('https://example.com/profile')
# 打印当前会话持有的 Cookie 字典
print(session.cookies.get_dict())
响应解析与故障排查
成功回调后,可通过响应对象的不同属性获取数据形态。开发中常遇网络抖动或协议错误,建议建立标准化拦截逻辑。
常用响应对象属性
response.status_code:HTTP 状态码整数(如 200、404、500)response.text:解码后的响应文本字符串response.content:原始字节流,适合下载文件response.json():自动反序列化为 Python 字典或列表
分级异常捕获模板
目的:精准定位连接层、超时层或协议层的失败原因,避免进程意外崩溃。
import requests
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status() # 状态码非 2xx 时主动抛出 HTTPError
data = response.json()
print(data)
except requests.exceptions.HTTPError as errh:
print(f"HTTP 错误:{errh}")
except requests.exceptions.ConnectionError as errc:
print(f"连接错误:{errc}")
except requests.exceptions.Timeout as errt:
print(f"请求超时:{errt}")
except requests.exceptions.RequestException as err:
print(f"其他请求错误:{err}")
启用 Debug 模式查看完整报文
当接口联调出现无法解释的 4xx/5xx 错误或验签失败时,底层 HTTP 客户端的 Debug 日志能直观展示请求头、载荷与服务器原始响应。通过注入 logging 与 http.client 钩子即可开启。
import http
import logging
import requests
# 提升日志级别并开启底层 Socket 调试
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('requests').setLevel(logging.DEBUG)
http.client.HTTPConnection.debuglevel = 1
resp = requests.get("http://jsonplaceholder.typicode.com/posts/3")
if resp.status_code == 200:
print(resp.json())
以上就是 Python 使用 requests 库发起 HTTP 请求的详细内容,更多关于 Python 网络编程的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









