特点
和使用 requests 一样方便,requests 有的它都有
加入 HTTP/1.1 和 HTTP/2 的支持。
既能发送同步请求,也能发送异步请求
安装
pip install httpx # 如果需要对 HTTP/2.0 支持,我们需要额外安装一个库 pip install httpx[http2]
基本使用
基本用法
用法和 requests 里的一模一样,将返回结果赋值为 response 变量,然后打印出它的 status_code、headers、text 等属性
请求
import httpx response = httpx.get('https://www.httpbin.org/get') print(response.status_code) print(response.headers) print(response.text)
上传文件
response = httpx.post("http://httpbin.org/post",files={"file": open("1.txt", "rb")})
重定向
httpx 里面的参数叫 follow_redirects,默认为 False,表示不进行重定向。如果希望重定向,那么将其设置为 True
response = httpx.get("http://www.taobao.com",follow_redirects=True) print(response.status_code)
http/2.0
httpx默认是不会开启对 HTP/2.0 的支持的,默认使用的是 HTTP/1.1,需要手动声明一下才能使用 HTTP/2.0
import httpx # 声明使用 http/2.0 client = httpx.Client(http2=True) response = client.get('https://spa16.scrape.center/') print(response.text)
Client 对象
和 requests 中的 Session 对象差不多
如果对同一个网站发送多次请求,client会继续保持原有的tcp连接来提高效率。
可以将headers、cookies、params等参数放在httpx.Client()中,在client下的请求共享这些配置参数
import httpx headers1 = {'x-auth': 'from-client'} params1 = {'client_id': '1234'} url = 'https://example.com' with httpx.Client(headers=headers1, params=params1) as client: headers2 = {'x-custom': 'from-request'} params2 = {'request_id': '4321'} r1 = client.get(url) print(r1.request.headers) r2 = client.get(url, headers=headers2, params=params2) print(r2.request.headers)
# 通过BaseUrl ,设置基础URL url = 'https://www.httpbin.org/headers' a = httpx.Client(base_url=url) res = a.get("aaa") print(res.url) res2 = a.get("adas") print(res2.url)
关闭 连接池:client.close()
client = httpx.Client() try: response = client.get('http://localhost:5000/details') finally: client.close()
异步支持
默认情况下,httpx使用标准的同步请求方式,如果需要的话,我们也可以使用它提供的异步client来发送相关请求。
使用异步client比使用多线程发送请求更加高效,更能体现明显的性能优势,并且它还支持WebSocket等长网络连接。
异步请求
使用 async / await 语句来进行异步操作,创建一个httpx.AsyncClient()对象
import asyncio import httpx async def main(): async with httpx.AsyncClient() as client: # 创建一个异步client r = await client.get('https://www.example.com/') print(r) if __name__ == '__main__': asyncio.run(main())
http代理
httpx可以通过设置proxies参数来使用http代理,我们也可以使用不同的代理来分别处理http和https协议的请求,假设有如下两个代理
import httpx proxies = { 'http://': 'http://localhost:8080', # 代理1 'https://': 'http://localhost:8081', # 代理2 } url = 'https://example.com' with httpx.Client(proxies=proxies) as client: r1 = client.get(url) print(r1)
注意,httpx的代理参数proxies只能在httpx.Client()中添加,client.get()是没有这个参数的。
超时处理
默认情况下,httpx到处都做了严格的超时处理,默认时间为5秒,超过5秒无响应则报TimeoutException
超时设置
# 普通请求: httpx.get('http://example.com/api/v1/example', timeout=10.0) # client实例: with httpx.Client() as client: client.get("http://example.com/api/v1/example", timeout=10.0)
关闭超时处理
# 普通请求: httpx.get('http://example.com/api/v1/example', timeout=None) # client实例: with httpx.Client() as client: client.get("http://example.com/api/v1/example", timeout=None)
ssl验证
当请求https协议的链接时,发出的请求需要验证所请求主机的身份,因此需要SSL证书来取得服务器的信任,如果要使用自定义的CA证书,则可以使用verify参数
import httpx r = httpx.get("https://example.org", verify="path/to/client.pem")