requests 是一个用于发送 HTTP 请求的 Python 库。它允许你发送 HTTP/1.1 请求,无需复杂的多层编码,使用起来非常简单直观。这个库支持各种类型的 HTTP 请求(GET, POST, PUT, DELETE, etc.),cookies, 会话, 重定向处理等,并且它支持身份验证机制以及请求时间设置等功能。

1 安装

你可以通过 pip 来安装 requests:

1
pip install requests

2 基本使用方法

2.1 发送 GET 请求

1
2
3
4
import requests

response = requests.get('http://httpbin.org/get')
print(response.text)

2.2 发送 POST 请求

1
2
response = requests.post('http://httpbin.org/post', data={'key':'value'})
print(response.text)

2.3 处理响应数据

1
2
3
4
5
6
7
8
9
10
11
12
# 获取响应状态码
print(response.status_code)

# 获取响应头
print(response.headers)

# 获取响应体
print(response.text) # 获取文本形式的数据
print(response.content) # 获取字节形式的数据

# 解析 JSON 格式的数据
print(response.json())

2.4 设置请求头部信息

1
2
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get('http://httpbin.org/headers', headers=headers)

2.5 设置请求参数

1
2
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://httpbin.org/get', params=payload)

2.6 处理 cookies

1
2
response = requests.get('http://httpbin.org/cookies')
print(response.cookies['example'])

2.7 文件上传

1
2
files = {'file': open('report.csv', 'rb')}
response = requests.post('http://httpbin.org/post', files=files)

2.8 会话维持

如果你需要跨多个请求维护某些参数,比如 cookies 或者设置认证信息,可以使用 Session 对象来实现。

1
2
3
4
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
response = s.get("http://httpbin.org/cookies")
print(response.text)

2.9 超时设置

1
response = requests.get('http://github.com', timeout=3)

3 注意事项

  • 在使用 requests 发送网络请求时,请确保目标服务器地址是正确的,并且能够正常访问。
  • 对于敏感操作,请确保 HTTPS 连接的安全性,可以使用 verify=True 参数来启用 SSL 证书验证。
  • 在处理大型文件或大量数据时,请注意内存使用情况,避免程序因占用过多资源而崩溃。

以上就是 requests 库的一些基本使用方法。更多高级功能和详细用法可以参考官方文档。