什么是 Requests?
Requests 是一个用 Python 编写的开源 HTTP 客户端库,由 Kenneth Reitz 创建并维护。它的设计哲学是"为人类设计",强调代码的可读性和易用性。使用 Requests,你可以用几行代码完成复杂的 HTTP 操作。
"Requests is the only Non-GMO HTTP library for Python, safe for human consumption."
------ 官方网站(https://requests.readthedocs.io)
安装 Requests
Requests 不是 Python 标准库的一部分,因此需要通过 pip 安装:
python
pip install requests
安装完成后,在 Python 脚本中导入即可使用:
python
import requests
基本用法
1. 发送 GET 请求
GET 请求是最常见的 HTTP 方法,用于从服务器获取数据。
python
response = requests.get('https://httpbin.org/get')
print(response.status_code) # 输出状态码,如 200
print(response.text) # 输出响应文本
你也可以传递查询参数(query parameters):
python
params = {'name': 'Alice', 'age': 25}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url) # https://httpbin.org/get?name=Alice&age=25
2. 发送 POST 请求
POST 请求常用于提交表单或发送数据到服务器。
python
data = {'username': 'Bob', 'password': '123456'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json()) # 将响应解析为 JSON
如果要发送 JSON 数据,可以使用 json 参数:
python
json_data = {'title': 'Hello', 'body': 'World'}
response = requests.post('https://httpbin.org/post', json=json_data)
3. 处理响应内容
Requests 提供了多种方式来处理服务器返回的数据:
response.text:以字符串形式返回响应内容(自动解码)。response.content:以字节形式返回原始内容,适合下载图片、文件等。response.json():将响应解析为 Python 字典或列表(要求响应是合法 JSON)。response.status_code:HTTP 状态码(如 200、404、500)。response.headers:响应头信息,是一个字典。
示例:下载一张图片
python
response = requests.get('https://example.com/image.jpg')
with open('image.jpg', 'wb') as f:
f.write(response.content)
高级功能
1. 自定义请求头
你可以通过 headers 参数设置自定义请求头,比如伪装成浏览器访问:
python
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get('https://httpbin.org/headers', headers=headers)
print(response.json())
2. 使用 Cookie 和 Session
对于需要保持登录状态的场景,可以使用 Session 对象:
python
session = requests.Session()
session.post('https://httpbin.org/login', data={'user': 'admin'})
# 后续请求会自动携带 Cookie
response = session.get('https://httpbin.org/dashboard')
3. 处理超时和异常
网络请求可能因网络问题失败,建议设置超时时间并捕获异常:
python
try:
response = requests.get('https://httpbin.org/delay/2', timeout=3)
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
4. 上传文件
使用 files 参数可以轻松上传文件:
python
files = {'file': open('report.pdf', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
实际应用示例
假设我们要从 GitHub API 获取某个用户的公开信息:
python
import requests
def get_github_user(username):
url = f'https://api.github.com/users/{username}'
response = requests.get(url)
if response.status_code == 200:
user = response.json()
print(f"用户名: {user['login']}")
print(f"公开仓库数: {user['public_repos']}")
print(f"关注者: {user['followers']}")
else:
print("用户未找到")
get_github_user('octocat')
总结
Requests 是 Python 中最流行的 HTTP 库之一,以其简洁的语法和强大的功能赢得了广大开发者的喜爱。它极大地简化了网络请求的编写过程,使开发者能够专注于业务逻辑而非底层细节。
主要优点:
- 语法简洁,易于学习和使用
- 支持各种 HTTP 方法和特性(如 Sessions、Cookies、文件上传等)
- 社区活跃,文档完善
- 广泛应用于爬虫、API 调用、自动化测试等领域
参考资料:
- 官方文档:https://requests.readthedocs.io
- GitHub 项目:https://github.com/psf/requests