0202httpx
request、urllib不支持http2.0协议,这时得用httpx.
安装httpx
1
2
3
pip3 install httpx #这种安装不支持http2
pip install "httpx[http2]" #支持http2
使用:
httpx的api设计接近requests
1
2
3
4
5
6
import httpx
r=httpx.get('https://www.httpbin.org/get') #data、headers、cookies、proxies
print(r.status_code)
print(r.headers)
print(r.txt)
print(r.http_version)#打印http version
请求http2(默认 httpx 未打开http2协议)
1
2
3
4
5
import httpx
with httpx.Client(http2=True) as client: #client需要关闭掉
r=client.get('https://spa16.scrape.center')
print(r.text)
httpx.Client中传递 headers
参数 p77
1
2
3
4
5
6
7
import httpx
headers={'User-Agent':'my-app/0.0`'}
with httpx.Client(headers=headers) as client: #client需要关闭掉
r=client.get('https://www.httpbin.org/headers')
json=r.json()#将返回文本转换成json对象
print(json['headers']['User-Agent'])
异步请求httpx.AnycClient p78
1
2
3
4
5
6
7
8
9
10
import httpx
import asyncio
async def fetch(url):
async with httpx.AsyncClient(http2=True) as client:
r=await client.get(url)
print(r.text)
if __name__=="__main__":
asyncio.get_event_loop().run_until_complete( fetch('https://www.httpbin.org/get') )
This post is licensed under CC BY 4.0 by the author.