requests
关于 Python Requests
Requests 是一个优雅而简单的 Python HTTP 库,在 Requests 的帮助下,开发者能够方便快捷地完成诸如发送 GET/POST 请求、处理 Cookies 和文件上传等常见的网络任务。
⚠️注意
Requests 支持 Python 3.7+,不再支持 Python 2;不支持 Http 2.0。
# 安装 Requests
通过 pip 命令安装:
pip install requests
1
通过源码安装:
git clone git://github.com/kennethreitz/requests.git
cd requests
pip install .
1
2
3
2
3
# 快速开始
Requests 支持 GET、POST、PUT、DELETE、HEAD、OPTIONS 等 HTTP 请求。
import requests
response = requests.get('https://httpbin.org/get')
response = requests.delete('https://httpbin.org/delete')
response = requests.head('https://httpbin.org/get')
response = requests.options('https://httpbin.org/get')
response = requests.post('https://httpbin.org/post', data={'key': 'value'})
response = requests.put('https://httpbin.org/put', data={'key': 'value'})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 设置代理
不需要账号密码验证:
import requests
host = '127.0.0.1:7890'
proxies = {
'http': f'http://{host}/',
'https': f'http://{host}/'
}
url = 'https://httpbin.org/get'
response = requests.get(url, proxies=proxies)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
需要账号密码验证:
import requests
username = 'username'
password = 'password'
host = '127.0.0.1:7890'
proxies = {
'http': f'http://{username}:{password}@{host}/',
'https': f'http://{username}:{password}@{host}/'
}
url = 'https://httpbin.org/get'
response = requests.get(url, proxies=proxies)
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 传递 URL 参数
import requests
params = {
'key1': 'value1',
'key2': ['value2', 'value3'],
}
url = 'https://httpbin.org/get'
response = requests.get(url, params=params)
print(response.url)
# https://httpbin.org/get?key1=value1&key2=value2&key2=value3
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# POST 请求
import requests
response = requests.post('https://httpbin.org/post', data={'key': 'value'})
1
2
3
4
2
3
4
帮助我们改善此页 (opens new window)
上次更新: 2024/10/17, 09:54:53