python爬虫学习24
四、httpx的使用
4-1.引入
截止目前我们一同学习了urllib库的使用、requests库的使用、以及正则表达式的相关内容。在这里就不得不提到urllib库与requests库的局限性:两者只支持HTTP/1.1,并不支持HTTP/2.0。一旦我们遇到仅支持HTTP/2.0的网站那就又废了。
# 此网站就是一个强制使用HTTP/2.0的网站
url = 'https://spa16.scrape.center/'
import requests
resp = requests.get(url)
print(resp.text)
运行结果:
为了应对这种困境,我们就不得不使用能够支持HTTP2.0的工具——httpx库
4.2 httpx库的安装
老样子,先安装一波
pip install httpx # 先安装 httpx 库
pip3 install httpx[http2] # 然后安装 httpx对HTTP2.0的支持模块
4.3 基本使用
httpx库的使用方式与requests是非常类似的:
import httpx
url = 'https://www.baidu.com'
resp = httpx.get(url)
print(resp.status_code)
print(resp.headers)
print(resp.text)
运行结果:
好!很有精神! 来让我试试之前连接不上的连接:
import httpx
url = 'https://spa16.scrap.center/'
resp = httpx.get(url)
print(resp.status_code)
print(resp.headers)
print(resp.text)
运行结果:
发生什么事了?为什么还是不行?
别着急,实际上httpx默认状态下是不会开启对HTTP2.0的支持的,这时候就需要我们手动开启了:
import httpx
url = 'https://spa16.scrape.center/'
c = httpx.Client(http2=True)
resp = c.get(url)
print(resp.text)
运行结果:
前文提到过,httpx库与requests库非常相似,所以类似的,httpx库下面也有post(),put(),delete(),patch()等方法,大家可以自行尝试。
绝对不是我偷懒了啊!
今日结束,明日继续