解决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.通过装饰器给函数设置一个最大执行超时时间
当函数执行时间超过某个时间就抛出 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) # 函数最大执行时间 5sdef test(): time.sleep(20)def run(): try: test() print('test 函数执行完成') except func_timeout.exceptions.FunctionTimedOut: print('test 函数执行超时')run() |
如上面例子那样,在 httpx.Client 所在函数设置一个额外等待时间,当该函数执行时间超过某个时间,就强制抛出 timeout 异常,避免程序无限阻塞。
python爬虫httpx的用法
安装命令:pip install httpx
请求方式
GET
| 1 2 3 4 5 6 |
import httpxheaders = {'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') |
以上为个人经验,希望能给大家一个参考,









