在日常开发中,经常会发送各种各样的网络请求。Python中常用的网络请求库有requests
、aiohttp
、httpx
等,httpx
是基于Python3的新一代的网络请求库,它的功能很丰富,做个简答的介绍。
httpx是Python新一代的网络请求库,它包含以下特点
特点
- 基于Python3的功能齐全的http请求模块
- 既能发送同步请求,也能发送异步请求
- 支持HTTP/1.1和HTTP/2
- 能够直接向WSGI应用程序或者ASGI应用程序发送请求
安装
httpx需要Python3.6+(使用异步请求需要Python3.8+)
pip3 install httpx
如果需要使用HTTP/2,则需要安装http2的相关依赖
pip3 install httpx[http2]
简单使用
httpx与requests库的基本使用方法几乎是一模一样的
import httpx
r = httpx.get('https://httpbin.org/get')
print(r)
类似的,我们也可以使用POST, PUT, DELETE, HEAD和OPTIONS等请求方法,如下
r = httpx.post('https://httpbin.org/post', data={'key': 'value'})
r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
r = httpx.delete('https://httpbin.org/delete')
r = httpx.head('https://httpbin.org/get')
r = httpx.options('https://httpbin.org/get')
带有请求头和请求参数的请求
import httpx
headers = {'user-agent': 'my-app/1.0.0'}
params = {'key1': 'value1', 'key2': 'value2'}
url = 'https://httpbin.org/get'
r = httpx.get(url, headers=headers, params=params)
print(r)
print(r.status_code) # 状态码
print(r.encoding) # 文本编码
print(r.text)
print(r.json())
结果如下
<Response [200 OK]>
200
ascii
{
"args": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "my-app/1.0.0",
"X-Amzn-Trace-Id": "Root=1-6139b788-2fd67d5627a5f6de346e154a"
},
"origin": "113.110.227.200",
"url": "https://httpbin.org/get?key1=value1&key2=value2"
}
{'args': {'key1': 'value1', 'key2': 'value2'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'my-app/1.0.0', 'X-Amzn-Trace-Id': 'Root=1-6139b788-2fd67d5627a5f6de346e154a'}, 'origin': '113.110.227.200', 'url': 'https://httpbin.org/get?key1=value1&key2=value2'}
请求带有cookies
import httpx
url = 'http://httpbin.org/cookies'
cookies = {'color': 'green'}
r = httpx.get(url, cookies=cookies)
print(r.json()) # {'cookies': {'color': 'green'}}
设置超时时间
import httpx
r = httpx.get('http://httpbin.org', timeout=0.001)
print(r)