第二章 基本库的使用之httpx

requests和urllib只能在HTTP1.0和HTTP1.1上请求,对于HTTP2.0的网站无能为力,有一些网站是强制HTTP2.0的,所以就需要用到httpx这个库。不过httpx和requests库的使用基本一致,只需要在使用前手动声明一下使用HTTP/2.0

import httpx

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

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
}
# 官方推荐的with as 使用方式
with httpx.Client(headers=headers) as client:
    response = client.get('https://www.httpbin.org/get')
    print(response)
'''
等价于
'''
import httpx

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
}
client = httpx.Client(headers=headers)
try:
    response = client.get('https://www.httpbin.org/get')
finally:
    client.close()

可以通过response.http_version属性来查看协议

httpx还支持异步请求

你可能感兴趣的:(第二章 基本库的使用之httpx)