Python requests库使用指南

360影视 动漫周边 2025-05-04 19:31 2

摘要:Python 的Requests库是一个简单易用的 HTTP 客户端库,广泛用于发送 HTTP 请求和处理响应。以下是它的核心用法和常见场景的示例:

Python 的 Requests 库是一个简单易用的 HTTP 客户端库,广泛用于发送 HTTP 请求和处理响应。以下是它的核心用法和常见场景的示例:

1. 安装 requests

bash

pip install requests

2. 基本 GET 请求

python

import requests

response = requests.get("https://api.example.com/data")

print(response.status_code) # 状态码(200表示成功)

print(response.text) # 响应内容(文本格式)

print(response.json) # 如果响应是 JSON,直接解析为字典

3. 传递 URL 参数

使用 params 参数自动编码查询字符串:

python

params = {"key1": "value1", "key2": "value2"}

response = requests.get("https://api.example.com/data", params=params)

4. 基本 POST 请求

发送表单数据或 JSON 数据:

python

# 表单数据

data = {"key": "value"}

response = requests.post("https://api.example.com/post", data=data)

# JSON 数据

json_data = {"key": "value"}

response = requests.post("https://api.example.com/post", json=json_data)

5. 设置请求头

python

headers = {"User-Agent": "my-app/1.0", "Authorization": "Bearer YOUR_TOKEN"}

response = requests.get("https://api.example.com/data", headers=headers)

6. 处理响应

python

response = requests.get(...)

# 检查请求是否成功

response.raise_for_status # 如果状态码不是200,抛出异常

# 获取内容

text_content = response.text # 文本格式

binary_content = response.content # 二进制格式(如图片)

json_content = response.json # 解析为字典(需响应是JSON)

# 获取响应头

print(response.headers["Content-Type"])

7. 处理超时

设置请求超时时间(秒):

python

try:

response = requests.get("https://api.example.com/data", timeout=5)

except requests.Exceptions.Timeout:

print("请求超时!")

8. 会话保持(Session)

复用 TCP 连接,保留 Cookies 和头信息:

python

with requests.Session as session:

session.headers.update({"User-Agent": "my-app/1.0"})

session.get("https://api.example.com/login", params={"user": "name", "pwd": "secret"})

response = session.get("https://api.example.com/protected-data")

9. 处理文件上传

python

files = {"file": open("example.txt", "rb")}

response = requests.post("https://api.example.com/upload", files=files)

10. 代理设置

python

proxies = {

"http": "http://10.10.1.10:3128",

"https": "http://10.10.1.10:1080",

}

response = requests.get("http://example.com", proxies=proxies)

11. 错误处理

python

try:

response = requests.get("https://api.example.com/data")

response.raise_for_status # 检查 HTTP 错误(4xx/5xx)

except requests.exceptions.HTTPError as http_err:

print(f"HTTP错误: {http_err}")

except requests.exceptions.RequestException as err:

print(f"请求异常: {err}")

12. 禁用 SSL 验证(仅测试环境)

python

response = requests.get("https://api.example.com", verify=False)

13. 重定向控制

禁用自动重定向:

python

response = requests.get("https://example.com", allow_redirects=False)

14. 流式下载大文件

分块读取响应内容,避免内存占用过高:

python

response = requests.get("https://example.com/large-file", stream=True)

with open("large_file.zip", "wb") as f:

for chunk in response.iter_content(chunk_size=8192):

f.write(chunk)

总结

requests 提供了简洁的 API 满足大多数 HTTP 交互需求,适合快速开发。对于高频次或异步场景,可考虑 aiohttp(异步)或 (兼容同步/异步)

来源:老客数据一点号

相关推荐