🐍
Python Requests模块完全指南
编程小白也能轻松掌握的HTTP请求库,用最简单的方式与网络世界对话
安装Requests模块
在开始之前,你需要安装requests库。打开终端或命令提示符,输入以下命令:
pip install requests
安装完成后,你就可以在Python程序中导入并使用它了:
import requests
1. 发送基本HTTP请求
GET请求 – 获取数据
GET是最常用的请求方法,用于从服务器获取数据。
import requests
# 发送一个简单的GET请求
response = requests.get(‘https://api.example.com/data’)
POST请求 – 提交数据
POST用于向服务器提交数据,如表单提交。
# 发送一个简单的POST请求
data = {‘username’: ‘john’, ‘password’: ‘secret’}
response = requests.post(‘https://api.example.com/login’, data=data)
提示: 除了GET和POST,Requests还支持其他HTTP方法:PUT, DELETE, HEAD, OPTIONS等,用法类似。
2. 处理服务器响应
检查响应状态
每个HTTP响应都有状态码,告诉我们请求是否成功:
# 检查请求是否成功 (200状态码表示成功)
if response.status_code == 200:
print(“请求成功!”)
else:
print(f”请求失败,状态码:{response.status_code}”)
# 更简单的检查方式
if response.ok:
print(“请求成功!”)
获取响应内容
获取服务器返回的数据:
# 获取文本内容(如HTML页面)
content = response.text
# 获取JSON数据(API常用)
data = response.json()
# 获取原始二进制内容(如图片)
image_data = response.content
响应头信息
查看服务器返回的头部信息:
# 获取所有响应头
headers = response.headers
# 获取特定响应头
content_type = response.headers[‘Content-Type’]
3. 设置请求参数和头部
URL参数
在URL中添加查询参数:
# 手动构建URL(不推荐)
url = ‘https://api.example.com/search?q=python&page=1’
# 更好的方式:使用params参数
params = {‘q’: ‘python’, ‘page’: 1}
response = requests.get(‘https://api.example.com/search’, params=params)
自定义请求头
设置自定义HTTP头部,如User-Agent或Authorization:
headers = {
‘User-Agent’: ‘MyApp/1.0’,
‘Authorization’: ‘Bearer YOUR_TOKEN’,
‘Accept’: ‘application/json’
}
response = requests.get(‘https://api.example.com/data’, headers=headers)
注意: 设置合适的User-Agent很重要,有些网站会拒绝没有User-Agent的请求。
4. 处理JSON数据和文件
发送JSON数据
向API发送JSON格式的数据:
payload = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
# 自动设置Content-Type为application/json
response = requests.post(‘https://api.example.com/users’, json=payload)
上传文件
上传文件到服务器:
# 打开文件并以二进制形式上传
with open(‘report.pdf’, ‘rb’) as file:
files = {‘file’: (‘report.pdf’, file, ‘application/pdf’)}
response = requests.post(‘https://api.example.com/upload’, files=files)
下载文件
从网络下载文件并保存:
url = ‘https://example.com/image.jpg’
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
with open(‘image.jpg’, ‘wb’) as file:
file.write(response.content)
print(“文件下载成功!”)
5. 错误和异常处理
Requests异常类型
Requests可能引发以下异常:
- requests.exceptions.RequestException: 所有requests异常的基类
- ConnectionError: 网络连接问题
- Timeout: 请求超时
- HTTPError: HTTP状态码不是200
异常处理示例
try:
response = requests.get(‘https://api.example.com/data’, timeout=5)
response.raise_for_status() # 如果状态码不是200,抛出HTTPError异常
# 处理响应数据
data = response.json()
print(data)
except requests.exceptions.Timeout:
print(“请求超时,请稍后重试”)
except requests.exceptions.HTTPError as err:
print(f”HTTP错误: {err}”)
except requests.exceptions.RequestException as err:
print(f”请求出错: {err}”)
重要: 在实际项目中,良好的错误处理至关重要,可以使你的程序更加健壮。
6. 高级用法和技巧
使用会话(Session)
Session可以保持一些参数和Cookie,提高效率:
# 创建一个Session对象
with requests.Session() as session:
# 设置Session级别的参数
session.headers.update({‘User-Agent’: ‘MyApp/1.0’})
# 第一次请求(会保持Cookie)
session.get(‘https://example.com/login’, params={‘user’: ‘john’})
# 后续请求自动使用相同的Cookie
response = session.get(‘https://example.com/dashboard’)
设置超时
防止请求长时间挂起:
# 设置连接超时和读取超时(单位:秒)
response = requests.get(‘https://api.example.com/data’, timeout=(3.05, 27))
SSL证书验证
处理HTTPS请求的证书验证:
# 禁用SSL证书验证(不推荐,除非必要)
response = requests.get(‘https://example.com’, verify=False)
# 指定自定义CA证书
response = requests.get(‘https://example.com’, verify=’/path/to/cert.pem’)
代理设置
proxies = {
‘http’: ‘http://10.10.1.10:3128’,
‘https’: ‘http://10.10.1.10:1080’,
}
requests.get(‘http://example.org’, proxies=proxies)
常见HTTP状态码速查表
状态码 | 名称 | 含义 |
---|---|---|
200 | OK | 请求成功 |
201 | Created | 资源创建成功 |
304 | Not Modified | 资源未修改(缓存有效) |
400 | Bad Request | 客户端请求有错误 |
401 | Unauthorized | 需要身份验证 |
403 | Forbidden | 服务器拒绝请求 |
404 | Not Found | 请求的资源不存在 |
500 | Internal Server Error | 服务器内部错误 |
503 | Service Unavailable | 服务不可用 |
Requests vs. Python内置urllib
为什么Requests比Python内置的urllib模块更受欢迎?
对比优势:
- 更简洁的API: Requests的API设计更符合人类直觉
- 自动内容解码: 自动处理文本编码问题
- JSON支持: 内置JSON解析器
- 连接池: 默认支持HTTP连接池
- 更好的错误处理: 更清晰的异常体系
- 国际化域名: 完美支持国际化域名和URL
一句话总结:Requests让HTTP请求变得简单优雅!