httpx基于异步框架,性能优于requests。本文主要介绍了在python中使用request发送http请求
更新于 2021-06-14
安装
发送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)
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
| r.url
r.text
r.encoding = "ISO-8859-1"
r.headers
r.http_version
r.status_code
r.json()
|
cookies
1 2 3 4 5 6 7 8 9 10
| >>> r = httpx.get("http://httpbin.org/cookies/set?chocolate=chip", allow_redirects=False) >>> r.cookies["chocolate"] 'chip'
>>> 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)
|