解決Python httpx 運行過程中無限阻塞的問題
時間:2022-11-30 來源: 作者:多多魚啊 我要糾錯
Python httpx 運行過程中無限阻塞
requests 模塊只支持 http1,在遇到 http2 的數據接口的時候(某乎的搜索接口),需要采用支持http2 請求的模塊(如 httpx、hyper)。
本文是針對 httpx 在請求數據時,出現無限阻塞問題的一些處理方法。
httpx 的 timeout 有 bug,會導致腳本在運行一段時間后,出現線程阻塞卡死的問題(無限 timeout)。
1.通過 pm2 部署腳本
另外啟動一個腳本,定時對該腳本進行重啟操作。
舉個栗子:
| 1 2 3 4 5 6 |
import timeimport oswhile True: time.sleep(60 * 60) # 一小時重啟一次 os.system('pm2 restart test') |
這個方法有個不好的地方,在請求過程中,可能需要翻很多頁,如果不斷重啟腳本,可能導致無法翻到最后一頁。
2.通過裝飾器給函數設置一個最大執(zhí)行超時時間
當函數執(zhí)行時間超過某個時間就拋出 TimeOut 異常
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from func_timeout import func_set_timeoutimport func_timeoutimport time@func_set_timeout(5) # 函數最大執(zhí)行時間 5sdef test(): time.sleep(20)def run(): try: test() print('test 函數執(zhí)行完成') except func_timeout.exceptions.FunctionTimedOut: print('test 函數執(zhí)行超時')run() |
如上面例子那樣,在 httpx.Client 所在函數設置一個額外等待時間,當該函數執(zhí)行時間超過某個時間,就強制拋出 timeout 異常,避免程序無限阻塞。
python爬蟲httpx的用法
安裝命令:pip install httpx
請求方式
GET
| 1 2 3 4 5 6 |
import httpx?headers = {'user-agent': 'my-app/1.0.0'}params = {'key1': 'value1', 'key2': 'value2'}url = 'https://httpbin.org/get'r = httpx.get(url, headers=headers, params=params) |
POST
r = httpx.post('https://httpbin.org/post', data={'key': 'value'}) |
PUT
r = httpx.put('https://httpbin.org/put', data={'key': 'value'}) |
DELETE
r = httpx.delete('https://httpbin.org/delete') |
以上為個人經驗,希望能給大家一個參考,









