開篇
本文整理自《Python3 網絡爬蟲實戰》,主要是httpx的使用。
筆記整理
使用urllib庫requests庫的使用,已經可以爬取絕大多數網站的數據,但對于某些網站依然無能為力。
這是因為這些網站強制使用HTTP/2.0協議訪問,這時urllib和requests是無法爬取數據的,因為它們只支持HTTP/1.1,不支持HTTP/2.0。
安裝
- 使用下面命令安裝httpx
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package httpx[http2]
基本使用
get
import httpx# 定義重試次數
retry_count = 3
for i in range(retry_count):try:# 設置超時時間為 10 秒response = httpx.get('https://www.httpbin.org/get', timeout=10)print(response.status_code)print(response.headers)print(response.text)breakexcept httpx.RequestError as e:print(f"請求失敗,第 {i + 1} 次重試,錯誤信息: {e}")
else:print("多次重試后仍然失敗,請檢查網絡或服務器狀態。")
如果想要開啟對HTTP/2.0的支持,需要手動聲明一下:
import httpxclient = httpx.Client(http2=True)
response = client.get('https://spa16.scrape.center/')
print(response.text)
其他
上面實現的是GET請求,對于POST請求、PUT請求和DELETE請求來說,實現方式是類似的:
import httpxr = httpx.get('https://www.httpbin.org/get',params={'name': 'germey'})
r = httpx.post('https://www.httpbin.org/post',data={'name': 'germey'})
r = httpx.put('https://www.httpbin.org/put')
r = httpx.delete('https://www.httpbin.org/delete')
r = httpx.patch('https://www.httpbin.org/patch')
Client對象
httpx中的Client對象,可以和requests中的Session對象類比學習。
官方比較推薦的是with as 語句,示例如下:
import httpxwith httpx.Client() as client:response = client.get('https://www.httpbin.org/get')print(response)
這個用法等同于下面這種:
import httpxclient = httpx.Client()
try:response = client.get('https://www.httpbin.org/get')print(response)
finally:client.close()
另外,在聲明Client對象時可以指定一些參數,例如headers,這樣使用該對象發起的所有請求都會默認帶上這些參數配置:
import httpxurl = 'https://www.httpbin.org/headers'
headers = {'User-Agent': 'my-app/0.0.1'}
with httpx.Client(headers=headers) as client:response = client.get(url)print(response.json()['headers']['User-Agent'])
支持HTTP/2.0
要想開啟對HTTP/2.0的支持,需要將http2設置為true
import httpxclient = httpx.Client(http2=True)
response = client.get('https://www.httpbin.org/get')
print(response.text)
print(response.http_version)
支持異步請求
import httpx
import asyncioasync def fetch(url):async with httpx.AsyncClient(http2=True) as client:response = await client.get(url)print(response.text)if __name__ == '__main__':asyncio.get_event_loop().run_until_complete(fetch('https://www.httpbin.org/get'))
注
以上便是本篇筆記的所有整理,希望對您能有所幫助~
感謝閱讀!