RunTimError:Timeout context manager should be used in task——python3.8爬虫异步asyncio趟坑

博客讲述了在Python3.7之后版本中遇到的异步请求运行时错误,特别是`TimeoutContextManagerShouldBeUsedInTask`问题。作者通过调整事件循环的使用位置和更新aiohttp的超时设置来解决问题。此外,还提到了其他bug的修复,确保了异步抓取代码的正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
乍一看,全是运行时错误,RunTimError:Timeout context manager should be used in task

# 异步抓取代码
async def fetch(session, url, headers=None, timeout=10, binary=False):
    _headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0",
    }
    if headers:
        _headers = headers
    try:
        async with session.get(url, headers=_headers, timeout=timeout)as response:
            status = response.status
            html = await response.read()
            if not binary:
                encoding = cchardet.detect(html)['encoding']
                html = html.decode(encoding, errors='ignore')
            redirected_url = str(response.url)
    except Exception as e:
        msg = "Failed to download url:{}, time:{},\n\t exception:{},\n{}".\format(url, time.strftime('%H:%M:%S'),
                                                                                 str(type(e)), str(e))
        print(msg)
        html = ""
        status = 0
        redirected_url = url
    return status, html, redirected_url

解决


请教了经验丰富的大佬,

1.

一开始,拿事件循环传给fetch异步请求函数,是放在__init__构造函数里面
在这里插入图片描述
python3.7以后版本,所有涉及异步的代码都要放到async函数里面
在这里插入图片描述
于是放到了这里,

2.


python3.7以后aiohttptimeout不能直接是整数,需要用aiohttptimeout类型

timeout = aiohttp.ClientTimeout(total=10)

再解决了其他几个bug后,就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值