上一篇
Python Requests库完全指南 - HTTP请求发送教程
- Python
- 2025-08-09
- 1728
Python Requests库完全指南
高效发送HTTP请求的终极教程
Requests库简介
Requests是Python中最受欢迎的HTTP库,以简洁、人性化的API设计著称。相比Python内置的urllib库,Requests提供了更简洁的API和更强大的功能。
主要特点:
- 简单易用的API
- 自动内容解码
- 支持HTTP连接保持和连接池
- 国际化域名和URL
- 支持文件分块上传
- 完善的SSL/TLS验证
安装Requests库
使用pip命令安装:
pip install requests
发送GET请求
GET请求用于从服务器获取数据:
import requests
# 基本GET请求
response = requests.get('https://api.example.com/data')
# 带参数的GET请求
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/data', params=params)
# 打印响应内容
print(response.text)
处理GET响应
# 检查请求是否成功
if response.status_code == 200:
print("请求成功!")
# 获取响应内容的不同格式
print("文本格式:", response.text)
print("JSON格式:", response.json())
print("二进制内容:", response.content)
print("响应头:", response.headers)
发送POST请求
POST请求用于向服务器提交数据:
import requests
# 发送JSON数据
payload = {'username': 'admin', 'password': 'secret'}
response = requests.post('https://api.example.com/login', json=payload)
# 发送表单数据
form_data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', data=form_data)
# 上传文件
files = {'file': open('report.xlsx', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
处理HTTP响应
状态码检查
response = requests.get('https://api.example.com')
if response.status_code == 200:
print("Success!")
elif response.status_code == 404:
print("Not Found!")
JSON响应处理
response = requests.get('https://api.example.com/data.json')
data = response.json()
print(data['key'])
响应头信息
print("Content Type:", response.headers['Content-Type'])
print("Server:", response.headers.get('Server', 'Unknown'))
高级用法
设置请求头
headers = {
'User-Agent': 'MyApp/1.0',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Accept': 'application/json'
}
response = requests.get('https://api.example.com', headers=headers)
超时设置
# 设置连接超时和读取超时
try:
response = requests.get('https://api.example.com', timeout=(3.05, 27))
except requests.exceptions.Timeout:
print("请求超时!")
会话保持
# 使用Session对象保持会话和cookies
with requests.Session() as session:
session.headers.update({'User-Agent': 'MyApp/1.0'})
# 登录
session.post('https://api.example.com/login', data={'user': 'admin', 'pass': 'secret'})
# 后续请求会保持会话状态
response = session.get('https://api.example.com/dashboard')
错误处理
try:
response = requests.get('https://api.example.com', timeout=5)
response.raise_for_status() # 如果状态码不是200,将抛出HTTPError异常
except requests.exceptions.HTTPError as errh:
print("HTTP错误:", errh)
except requests.exceptions.ConnectionError as errc:
print("连接错误:", errc)
except requests.exceptions.Timeout as errt:
print("超时错误:", errt)
except requests.exceptions.RequestException as err:
print("请求异常:", err)
掌握Requests库,高效处理HTTP请求
Requests库简化了Python中的HTTP请求处理,是每个Python开发者必备的工具
本文由JiangKuang于2025-08-09发表在吾爱品聚,如有疑问,请联系我们。
本文链接:http://521pj.cn/20257689.html
发表评论