httpx基于异步框架,性能优于requests。本文主要介绍了在python中使用request发送http请求

更新于 2021-06-14


安装

1
$ pip install httpx

发送get请求

1
2
3
4
5
6
import httpx

params = {"key1": "value2", "key2": ["value2", "value3"]}
headers = {"user-agent": "my-app/0.0.1"}

r = httpx.get("https://www.example.com", params=params, headers=headers)

发送post请求

1
2
3
4
5
6
7
8
9
import httpx

headers = {"user-agent": "my-app/0.0.1"}
data={"key": "value"}

r = httpx.post("https://www.example.com", data=data, headers=headers)

# 发送json编码数据
r = httpx.post("https://www.example.com", json=data)

处理响应结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 打印请求url
r.url

# 响应内容
r.text

# 设置使用的编码
r.encoding = "ISO-8859-1"

# 响应头
r.headers

# 响应http版本
r.http_version

# 响应状态码
r.status_code

# 获取json内容
r.json()

cookies

1
2
3
4
5
6
7
8
9
10
# 获取cookies
>>> r = httpx.get("http://httpbin.org/cookies/set?chocolate=chip", allow_redirects=False)
>>> r.cookies["chocolate"]
'chip'

# 请求带cookie
>>> cookies = {"peanut": "butter"}
>>> r = httpx.get("http://httpbin.org/cookies", cookies=cookies)
>>> r.json()
{'cookies': {'peanut': 'butter'}}

cookies也可以按域进行访问设置:

1
2
3
4
5
6
>>> cookies = httpx.Cookies()
>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
>>> cookies.set('cookies_off_domain', 'nope', domain="example.org")
>>> r = httpx.get("http://httpbin.org/cookies", cookies=cookies)
>>> r.json()
{'cookies': {'cookie_on_domain': 'hello, there!'}}

用户身份认证

基本认证:

1
httpx.get("https://example.com", auth=("my_user", "password123"))

摘要式身份认证:

1
2
auth = httpx.DigestAuth("my_user", "password123")
httpx.get("https://example.com", auth=auth)