You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中page.click失败时如何退出async with块?break无效求解决

解决page.click失败时退出async with代码块的问题

你用break没用是因为break只能跳出循环或switch语句,而async with是上下文管理器,不属于循环结构,所以break对它无效。

可以用以下两种方式修改代码:

方式一:主动取消下载等待并抛出异常

try:
    async with page.expect_download(timeout=120000) as download_info:
        try:
            await page.click(First_Row_Download, timeout=3000)
        except Exception:
            # 主动取消下载等待,终止async with块
            download_info.cancel()
            # 抛出异常让外层捕获,进入刷新逻辑
            raise

    Download = await download_info.value
    await Download.save_as(Download.suggested_filename)
    Download_Finished = True
    break
except Exception:
    await page.wait_for_timeout(Wait_Time) # 3分钟
    await page.click(Button_Refresh)

方式二:去掉内部try-except,让click异常直接向外传播

这种方式更简洁,当click超时找不到元素时,异常会直接跳出async with块,进入外层的异常处理逻辑:

try:
    async with page.expect_download(timeout=120000) as download_info:
        await page.click(First_Row_Download, timeout=3000)

    Download = await download_info.value
    await Download.save_as(Download.suggested_filename)
    Download_Finished = True
    break
except Exception:
    await page.wait_for_timeout(Wait_Time) # 3分钟
    await page.click(Button_Refresh)

原理是:当page.click抛出异常时,async with上下文管理器会自动终止expect_download的等待,直接进入外层的异常处理逻辑,从而达到退出async with块的目的。

内容的提问来源于stack exchange,提问作者user19016544

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:25:22