跳至内容

快速上手 requests 库

Python 中,requests 是一个常用的第三方 HTTP 请求库,可以方便地向网站发送 HTTP 请求,并获取响应结果。

pip install requests

如果读者不了解 HTTP 协议,请查看HTTP 教程,对于理解本文内容有很大帮助。本文中可请求接口由JSONPlaceholder提供。

开发实践中,大多数开发者习惯只使用 GET 和 POST 请求方式,现在 Restful API 也渐渐流行。

发起请求

先简单看一下,如何发起一个 GET 请求。

1
2
3
4
5
6
7
8
import requests

# 定义url,获取id为1的文章
url = "https://jsonplaceholder.typicode.com/posts/1"

# 发起请求
response = requests.get(url) # GET方法
print(response.json()) # 输出“{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}”

请求参数

可以 URL 带参和请求体带参。Restful API 规范中,一般 GET 和 DELETE 请求方式在 URL 中带参,其余请求方式通过请求体带参。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import requests

# 定义url,获取文章列表
url = "https://jsonplaceholder.typicode.com/posts"
# 定义筛选参数
params = {"userId": 1}

# 发起请求,获取userId为1的文章,url带参
response = requests.get(url, params=params)  # GET方法
print(response.json())

# 定义新增文章参数
add_post = {"title": "测试新增文章", "body": "这是一篇新增文章。", "userId": 3}

# 发起新增文章请求,请求体带参
# 通过 json= 传参,请求头 Content-type: application/json; charset=UTF-8
response = requests.post(url, json=add_post)  # post方法

print(response.json())

除了 JSON 格式参数,当然也可以传其他格式参数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import requests

# 该地址不存在
url = "https://yanshi.com/add"
# 定义新增文章参数
formdata = {"name": "ALice", "age": "23。"}

# 通过 data= 传参,请求头 Content-Type: application/x-www-form-urlencoded
response = requests.post(url, data=formdata)
print(response.json())

# 通过 files= 传参,请求头 Content-Type: multipart/form-data
with open('python.jpg', 'rb') as f:
    files = {
        'file': ('python.jpg', f, 'image/jpeg'),
    }
    data = {
        'key1': 'value1',
        'key2': 'value2'
    }
    # 发起 POST 请求
    response = requests.post(url, files=files, data=data)
print(response.json())

# 请求头中指定 Content-Type,传对应格式参数
# XML 数据
xml_data = """
<note>
  <to>Friends</to>
  <from>JZY</from>
  <heading>Reminder</heading>
  <body>Don't forget me!</body>
</note>
"""

headers = {
    'Content-Type': 'application/xml'
}

# 发起 POST 请求
response = requests.post(url, data=xml_data, headers=headers)

请求头

请求体通过 headers= 传递。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"


headers = {
    'Content-Type': 'application/xml',
    'Authorization': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
}

response = requests.get(url, headers=headers)
print(response)

Cookies

在 HTTP 请求中,Cookies 是服务器发送给客户端的一小段数据,客户端会保存这些数据,并在后续请求中自动将其携带回服务器。它常用于身份验证、会话管理、用户追踪等场景。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"


# 假设定义的cookies是服务器需要的cookies
cookies = {
    'session_id': '9256304856',
    'visit_time': '2024-09-16'
}

response = requests.get(url, cookies=cookies)
print(response)

还可以使用 Session 对象管理 Cookies。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"


# 假设定义的cookies是服务器需要的cookies
cookies = {
    'session_id': '9256304856',
    'visit_time': '2024-09-16'
}

# 创建一个Session对象
session = requests.Session()
session.cookies.update(cookies)



# 后续发送请求,不需要指定cookies,因为它们已经被Session管理
response = session.get(url)
print(response)

Basic Auth

HTTP 请求中,Basic Auth(基本认证)是一种简单的身份验证机制,允许客户端在请求中直接提供用户名和密码作为身份凭证。它应该值是一个元组,包含两个元素,第一个是用户名(username),第二个是密码(password)。但安全性较低,常用于内部系统、测试环境或对安全性要求不高的场景。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"


# 定义认证信息
auth = ('Alice', 'uhg45dsg')

# 指定 auth
response = requests.get(url, auth=auth)
print(response)

响应超时

参数 time= 可以指定超时时间(默认为 None,一直等待),超时会抛出 Timeout 异常。如果 timeout 是一个数字,表示连接和读取的总超时时间。如果 timeout 是一个元组,它应该包含两个数值(支持浮点数),分别指定连接和读取的超时时间。例如,(3, 0.5)、(2.2, None)。

1
2
3
4
5
6
7
8
9
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"

# 如果超时会抛出 Timeout 异常
response = requests.get(url, timeout=5)

print(response)

重定向

参数 allow_redirects= 为 True(默认值),会自动处理服务器返回的所有重定向。否则(False),不自动处理重定向,而是将重定向响应返回给用户。

1
2
3
4
5
6
7
8
9
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"

# 不自动处理重定向
response = requests.get(url, allow_redirects=False)

print(response)

设置代理

如果需要网络代理,可以通过 proxies= 参数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"

# 定义代理信息
proxies = {
    'http': 'socks5://127.0.0.1:10808',
    'https': 'socks5://127.0.0.1:10808',
}

# 不自动处理重定向
response = requests.get(url, proxies=proxies)

print(response)

SSL 认证

参数 verify= 用于验证服务端的 SSL 证书。为 True 时(默认),证书无效或过期,将抛出一个 SSLError 异常。为 False 时,不会验证 SSL 证书。

参数 cert= 用于验证客户端的 SSL 证书。它的值可以是单个文件的路径(包含密钥和证书)或者一个元组(包含两个文件路径,一个为密钥,一个为证书)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import requests

# 定义url,该地址不存在,只为了演示
url = "https://yanshi.com/add"

# 不验证服务端的SSL证书
response = requests.get(url, verify=True)
print(response)

# 定义客户端证书的路径
cert_file = '/path/to/client_cert.pem'
response = requests.get(url, cert=cert_file)
print(response)

解析响应

响应由状态行、响应头、响应体组成,解析这些数据非常简单。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import requests

# 该接口可以调用
url = "https://jsonplaceholder.typicode.com/todos/1"

response = requests.get(url)
# 解析状态码
print(response.status_code)
# response.ok 方法可以判断响应的code是否为2xx,是返回True,不是返回False
print(response.ok)
# 解析响应头
print(response.headers)
# 解析响应体,如果响应消息是 JSON 格式,可以直接使用response.json(),返回类型为dict
print(response.json())
# 解析响应体,如果响应消息非 JSON 格式,使用 response.text
print(response.text)

参考