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

Selenium找不到元素时继续执行脚本,捕获异常仍报TimeoutException求助

问题原因

显式等待WebDriverWait在设定时间内未找到符合条件的元素时,抛出的是TimeoutException,你仅捕获了NoSuchElementException,异常未被拦截所以脚本直接中断。
你第一种直接判断元素变量的写法也无法生效:如果定位元素阶段就抛出异常,代码根本不会执行到if判断分支。


解决方案

  1. 先导入需要捕获的异常类
from selenium.common.exceptions import NoSuchElementException, TimeoutException
  1. 调整异常捕获逻辑,同时覆盖两种异常场景即可保证脚本不中断
try:
    wait = WebDriverWait(driver, 15)
    Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
    print('element found')
    # 元素存在时的业务逻辑写在此处
except (NoSuchElementException, TimeoutException):
    print('Element not found')
    # 元素不存在时的处理逻辑写在此处,无特殊处理可留空,脚本会继续向下执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:24:05