python爬虫学习25

python爬虫学习25

四、httpx库

接着昨天的进度继续:

上半部分的传送门

4-4 client 对象

httpx中有一个client对象,对于他的使用我们可以类比requests库中的session:

# client 对象
import httpx

with httpx.Client() as cli:
    resp = cli.get('https://www.httpbin.org/get')
    print(resp)

运行结果:

在这里插入图片描述

对于client 官方推荐的用法就是 with…as语句,但是我们也可以等价为下面:

# 等价为 ↓↓↓↓↓
import httpx

client = httpx.Client()
try:
    resp = client.get('https://www.httpbin.org/get')
    print(resp)
finally:
    client.close()

运行结果:

在这里插入图片描述

同时,在设置client对象时,还可以指定一些参数:

import httpx

url = 'http://www.httpbin.org/get'
headers = {
    
    'User-Agent': 'this is a user-agent'}
with httpx.Client(headers=headers) as client:
    resp = client.get(url)
    print(resp.json()['headers']['User-Agent'])

从网站返回的响应中,我们提取了设置的User-Agent字段,说明我们成功地赋值了headers属性:

在这里插入图片描述

4-5 支持HTTP/2.0

对于httpx对http/2.0的支持,我们在4-3中已经涉及过了:

import httpx

# 如果不设置http2字段 httpx库默认不会支持http2.0
client = httpx.Client(http2=True)
url1 = 'http://www.httpbin.org/get'
url2 = 'https://spa16.scrape.center/'
resp1 = client.get(url2)
print('resp1:', resp1.http_version)
resp2 = client.get(url1)
print('resp2:', resp2.http_version)
resp3 = httpx.get(url1)
print('resp3:', resp3.http_version)

运行结果:

在这里插入图片描述

对比以上三组结果,我们也可以得到一个结论:在设置HTTP2.0以后,只有服务器端客户端要求使用HTTP2.0时,它才会使用HTTP2.0进行传输,否则一般情况下(网页使用HTTP1.1就可以得到相应)即使已经设置对2.0的支持,它依然会使用HTTP1.1进行传输。

4-6 支持异步请求

httpx还支持异步客户端请求,支持python的async请求模式:

# 支持异步请求:

import httpx
import asyncio

async def fetch(url):
    async with httpx.AsyncClient(http2=True) as cli:
        resp = await cli.get(url)
        print(resp.text)
if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(fetch('http://www.httpbin.org/get'))

运行结果:

在这里插入图片描述

啥叫异步请求?不知道,学到那里的时候或许就知道了吧

至此对于httpx学习完毕,未完待续

猜你喜欢

转载自blog.csdn.net/szshiquan/article/details/123881699
今日推荐