<8> httpx基础

支持HTTP/2.0,异步

1.安装
pip install httpx[http2]

2.基本使用(类似requests)
httpx 默认使用的 HTTP/1.1,需要手动声明才能使用HTTP/2.0

import httpx

client = httpx.Client(http2=True)
response = client.get('https://spa16.scrape.center/')
print(response.text)

3.Client 对象
类似requests的session,在声明 Client 对象时可以指定参数

import httpx

with httpx.Client(http2=True) as client:
response = client.get('https://spa16.scrape.center/')

等价于====>>

import httpx

client = httpx.Client(http2=True)
try:
response = client.get('https://spa16.scrape.center/')
finally:
client.close()
print(response.text)

4.支持异步请求(了解)
官方文档: https://ww.python-httpx.org/async/

import httpx

import asyncio
async def start_url():
url = 'https://www.httpbin.org/get'
async with httpx.AsyncClient(http2=True) as client:
response = await client.get(url=url)
print(response.text)

if name == 'main':
asyncio.get_event_loop().run_until_complete(start_url())

posted on 2022-12-03 16:11  不是霉蛋  阅读(108)  评论(0)    收藏  举报