Python Requests 库
Python Requests库[编辑 | 编辑源代码]
Python Requests库 是一个简单易用的HTTP客户端库,用于发送各种HTTP请求(如GET、POST、PUT、DELETE等)并处理响应。它是Python生态中最流行的HTTP请求库之一,因其简洁的API和强大的功能而广受欢迎。Requests库抽象了底层的复杂操作,使开发者能够更专注于业务逻辑,而无需处理繁琐的HTTP协议细节。
安装 Requests[编辑 | 编辑源代码]
在开始使用Requests之前,需要先安装它。可以通过pip安装:
pip install requests
基本用法[编辑 | 编辑源代码]
Requests库的核心功能是发送HTTP请求并处理响应。以下是几种常见的HTTP请求方法及其用法。
GET 请求[编辑 | 编辑源代码]
GET请求用于从服务器获取数据。以下是一个简单的GET请求示例:
import requests
# 发送GET请求
response = requests.get('https://api.github.com')
# 打印响应状态码
print(response.status_code) # 输出:200
# 打印响应内容(JSON格式)
print(response.json())
输出示例:
200 {'current_user_url': 'https://api.github.com/user', ...}
POST 请求[编辑 | 编辑源代码]
POST请求用于向服务器提交数据。以下是一个POST请求示例,向服务器发送JSON数据:
import requests
# 定义要发送的数据
data = {'key1': 'value1', 'key2': 'value2'}
# 发送POST请求
response = requests.post('https://httpbin.org/post', json=data)
# 打印响应内容
print(response.json())
输出示例:
{'args': {}, 'data': '{"key1": "value1", "key2": "value2"}', ...}
其他HTTP方法[编辑 | 编辑源代码]
Requests库还支持PUT、DELETE、HEAD等HTTP方法,用法与GET和POST类似:
# PUT请求
response = requests.put('https://httpbin.org/put', data={'key': 'value'})
# DELETE请求
response = requests.delete('https://httpbin.org/delete')
# HEAD请求
response = requests.head('https://httpbin.org/get')
请求参数与头部[编辑 | 编辑源代码]
在实际应用中,通常需要传递参数或自定义请求头部。
查询参数[编辑 | 编辑源代码]
可以通过`params`参数传递URL查询参数:
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url) # 输出:https://httpbin.org/get?key1=value1&key2=value2
自定义头部[编辑 | 编辑源代码]
可以通过`headers`参数自定义请求头部:
headers = {'User-Agent': 'my-app/1.0'}
response = requests.get('https://httpbin.org/get', headers=headers)
print(response.json()['headers']['User-Agent']) # 输出:my-app/1.0
处理响应[编辑 | 编辑源代码]
Requests库提供了多种方法来处理响应数据。
响应内容[编辑 | 编辑源代码]
可以通过以下属性获取响应内容:
- `response.text`:返回文本内容(如HTML或JSON字符串)。
- `response.json()`:将JSON响应解析为Python字典。
- `response.content`:返回二进制内容(如图片或文件)。
response = requests.get('https://api.github.com')
print(response.text) # 输出JSON字符串
print(response.json()) # 输出解析后的字典
响应状态码[编辑 | 编辑源代码]
`response.status_code`返回HTTP状态码,常见的状态码包括:
- 200:请求成功。
- 404:资源未找到。
- 500:服务器内部错误。
if response.status_code == 200:
print("请求成功")
else:
print(f"请求失败,状态码:{response.status_code}")
高级功能[编辑 | 编辑源代码]
Requests库还提供了一些高级功能,如会话管理、超时设置和代理支持。
会话管理[编辑 | 编辑源代码]
使用`requests.Session()`可以保持会话状态(如Cookies):
session = requests.Session()
session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
response = session.get('https://httpbin.org/cookies')
print(response.json()) # 输出:{'cookies': {'sessioncookie': '123456789'}}
超时设置[编辑 | 编辑源代码]
可以通过`timeout`参数设置请求超时时间(单位:秒):
try:
response = requests.get('https://httpbin.org/delay/5', timeout=3)
except requests.exceptions.Timeout:
print("请求超时")
代理支持[编辑 | 编辑源代码]
可以通过`proxies`参数设置代理服务器:
proxies = {'http': 'http://proxy.example.com:8080'}
response = requests.get('https://httpbin.org/get', proxies=proxies)
实际案例[编辑 | 编辑源代码]
以下是一个实际应用场景:使用Requests库从GitHub API获取用户信息。
import requests
def get_github_user(username):
url = f'https://api.github.com/users/{username}'
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return None
user = get_github_user('octocat')
print(user['login']) # 输出:octocat
print(user['name']) # 输出:The Octocat
总结[编辑 | 编辑源代码]
Requests库是Python中处理HTTP请求的强大工具,适用于从简单的API调用到复杂的Web爬虫等各种场景。通过本文的介绍,你应该已经掌握了Requests库的基本用法和高级功能。接下来,可以尝试在实际项目中应用这些知识,例如调用REST API或构建自动化测试脚本。