Selenium找不到元素时继续执行脚本,捕获异常仍报TimeoutException求助
问题原因
显式等待WebDriverWait在设定时间内未找到符合条件的元素时,抛出的是TimeoutException,你仅捕获了NoSuchElementException,异常未被拦截所以脚本直接中断。
你第一种直接判断元素变量的写法也无法生效:如果定位元素阶段就抛出异常,代码根本不会执行到if判断分支。
解决方案
- 先导入需要捕获的异常类
from selenium.common.exceptions import NoSuchElementException, TimeoutException
- 调整异常捕获逻辑,同时覆盖两种异常场景即可保证脚本不中断
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
相关产品推荐
相关产品推荐

