requests 是 Python 中最流行、最易用的 HTTP 客户端库,用于向 Web 服务器发送 HTTP 请求(如 GET、POST 等)并处理响应。
📦 一、基本用法
1. 安装
pip install requests
2. 导入
import requests
🚀 二、发送请求(常用方法)
| 方法 | 用途 | 示例 |
|---|---|---|
requests.get(url) | 获取资源 | requests.get('https://httpbin.org/get') |
requests.post(url, data=json_data) | 提交数据 | requests.post('https://httpbin.org/post', json={'key': 'value'}) |
requests.put(url) | 更新资源(全量) | requests.put('https://httpbin.org/put', json={'name': 'Alice'}) |
requests.patch(url) | 更新资源(部分) | requests.patch('https://httpbin.org/patch', json={'age': 25}) |
requests.delete(url) | 删除资源 | requests.delete('https://httpbin.org/delete') |
📥 三、常用参数(发送请求时使用)
response = requests.get(
url,
params={'key': 'value'}, # 添加查询参数 → ?key=value
headers={'Authorization': 'Bearer token'}, # 自定义请求头
cookies={'session_id': '12345'}, # 发送 Cookie
auth=('user', 'pass'), # HTTP Basic 认证
json={'name': 'Alice'}, # 自动设置 Content-Type: application/json 并序列化
data={'key': 'value'}, # 发送表单数据(x-www-form-urlencoded)
files={'file': open('test.txt', 'rb')}, # 上传文件
timeout=10, # 超时时间(秒)
verify=True, # 是否验证 SSL 证书(False 可跳过验证,不推荐)
allow_redirects=True # 是否允许重定向
)
📤 四、Response 对象的常用属性和方法
当你调用 requests.get() 等方法后,会返回一个 Response 对象,包含服务器的响应信息。
| 属性/方法 | 类型 | 说明 | 示例 |
|---|---|---|---|
.status_code | int | HTTP 状态码 | 200, 404, 500 |
.ok | bool | 状态码是否在 200-299 之间(成功) | if response.ok: print("成功") |
.text | str | 响应的文本内容(字符串) | print(response.text) |
.content | bytes | 响应的原始字节内容(适合图片、文件) | with open('img.jpg', 'wb') as f: f.write(response.content) |
.json() | dict/list | 将响应内容解析为 Python 字典或列表(自动解码 JSON) | data = response.json() |
.headers | dict | 响应头信息(字典) | print(response.headers['Content-Type']) |
.url | str | 实际请求的 URL(可能因重定向而改变) | print(response.url) |
.cookies | RequestsCookieJar | 服务器返回的 Cookie | print(response.cookies) |
.elapsed | timedelta | 请求耗时 | print(response.elapsed) |
.encoding | str | 响应内容的编码 | response.encoding = 'utf-8'(可手动设置) |
✅ 五、完整使用示例
import requests
# 1. 发送 GET 请求
response = requests.get(
'https://httpbin.org/get',
params={'name': 'Alice', 'age': 25},
headers={'User-Agent': 'MyApp/1.0'},
timeout=5
)
# 2. 检查响应
if response.status_code == 200:
print("请求成功!")
print("状态码:", response.status_code)
print("URL:", response.url)
print("响应头:", response.headers)
# 解析 JSON 数据
data = response.json()
print("返回数据:", data)
else:
print(f"请求失败,状态码: {response.status_code}")
🛡 六、异常处理(推荐)
import requests
from requests.exceptions import RequestException, Timeout, ConnectionError
try:
response = requests.get('https://httpbin.org/get', timeout=3)
response.raise_for_status() # 如果状态码 >= 400,抛出 HTTPError
print(response.json())
except Timeout:
print("请求超时")
except ConnectionError:
print("连接失败")
except requests.exceptions.HTTPError as e:
print(f"HTTP 错误: {e}")
except RequestException as e:
print(f"其他请求错误: {e}")
🔄 七、会话(Session)——保持状态
如果你需要保持 Cookie、headers 等状态(如登录后操作),使用 Session:
session = requests.Session()
session.headers.update({'User-Agent': 'MyApp/1.0'})
# 登录
login_response = session.post('https://example.com/login', data={'user': 'alice', 'pass': '123'})
# 后续请求会自动携带登录后的 Cookie
profile = session.get('https://example.com/profile')
print(profile.json())
✅ 总结
| 类别 | 关键点 |
|---|---|
| 请求方法 | get, post, put, delete 等 |
| 常用参数 | params, headers, json, data, timeout |
| 响应属性 | .status_code, .text, .json(), .headers |
| 异常处理 | try-except 捕获 Timeout, ConnectionError 等 |
| 高级用法 | Session 保持会话状态 |
requests 库简洁、强大、易用,是 Python 爬虫、API 调用、自动化测试等场景的首选工具。
Python requests 使用详解
1278

被折叠的 条评论
为什么被折叠?



