Requests库简介
Requests是Python中最受欢迎的HTTP客户端库,以其简单直观的API设计而闻名。它支持多种HTTP请求方法(GET, POST, PUT, DELETE等)和各种类型的数据发送。
安装方法: 使用pip安装requests库:pip install requests
基本GET请求示例
import requests
# 发送GET请求
response = requests.get('https://api.example.com/data')
# 检查响应状态
if response.status_code == 200:
print("请求成功!")
print("响应内容:", response.text)
else:
print(f"请求失败,状态码: {response.status_code}")
发送不同类型数据的示例
Requests库可以发送多种类型的数据,包括表单数据、JSON、文件等。下面我们将详细介绍各种类型的发送方法。
1 发送表单数据
使用data
参数发送application/x-www-form-urlencoded格式的表单数据。
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json())
2 发送JSON数据
使用json
参数自动序列化字典为JSON格式,并设置正确的Content-Type头。
payload = {'name': 'John', 'age': 30, 'city': 'New York'}
response = requests.post('https://api.example.com/users', json=payload)
print(response.status_code)
3 上传文件
使用files
参数上传文件,支持单个或多个文件上传。
# 上传单个文件
with open('report.pdf', 'rb') as f:
response = requests.post('https://api.example.com/upload', files={'file': f})
# 上传多个文件
files = [
('images', ('image1.jpg', open('img1.jpg', 'rb'), 'image/jpeg')),
('images', ('image2.png', open('img2.png', 'rb'), 'image/png'))
]
response = requests.post('https://api.example.com/upload', files=files)
4 发送原始数据
使用data
参数发送原始字节数据,如XML或自定义格式数据。
# 发送XML数据
xml_data = '<person><name>John</name><age>30</age></person>'
headers = {'Content-Type': 'application/xml'}
response = requests.post('https://api.example.com/data',
data=xml_data, headers=headers)
print(response.text)
高级请求示例
设置请求头
自定义请求头可以传递认证信息、指定内容类型或设置其他HTTP标头。
headers = {
'User-Agent': 'MyApp/1.0',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
response = requests.get('https://api.example.com/protected', headers=headers)
处理响应
Requests提供了多种处理响应内容的方法:
response = requests.get('https://api.example.com/data')
# 获取文本内容
print(response.text)
# 获取二进制内容
print(response.content)
# 获取JSON响应(自动解析)
data = response.json()
print(data['key'])
# 获取响应头
print(response.headers['Content-Type'])
# 获取状态码
print(response.status_code)
处理超时和错误
在生产环境中,正确处理网络请求中的错误非常重要。
try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status() # 如果状态码不是200,抛出HTTPError
except requests.exceptions.Timeout:
print("请求超时!")
except requests.exceptions.HTTPError as err:
print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
print(f"请求异常: {err}")
总结
Requests库为Python开发者提供了简洁而强大的HTTP客户端功能。通过本教程,您应该已经掌握了:
- 如何发送GET和POST请求
- 发送表单数据、JSON数据和文件的方法
- 设置自定义请求头和超时
- 处理各种响应内容
- 错误处理的最佳实践
Requests库的更多高级功能,如会话保持、代理设置、Cookie管理等,可以参考官方文档。
发表评论