Selenium Python中如何捕获WebDriverWait抛出的TimeoutException
问题原因
- 异常捕获范围未覆盖抛错代码
你当前代码中,触发TimeoutException的WebDriverWait().until()逻辑写在了try块的外部。程序执行到这行时,如果等待超时抛出异常,会直接向外抛出中断脚本,根本不会进入后续编写的try-except逻辑,自然无法走到捕获分支输出fail。
你现有的try块仅包裹了print(a.text)这行代码,只能捕获这行执行过程中触发的NoSuchElementException、StaleElementReferenceException等异常,覆盖不到块外的等待逻辑。 - 关于TimeoutException与WebDriverWait的适配性
不存在不适配的问题:WebDriverWait等待超时后抛出的原生异常就是selenium.common.exceptions.TimeoutException,本身就是该场景下应当捕获的异常类型,用法本身没有错误。
修正方案
将所有可能抛出目标异常的代码(包括WebDriverWait等待逻辑、元素文本获取逻辑)全部移入try块内部,同时补上原代码遗漏的WebDriverWait导入:
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, TimeoutException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://www.google.com/') try: # WebDriverWait逻辑移入try块后,超时抛出的异常会被当前块捕获 a = WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.XPATH, '//*[@class="gLFyf gsfi"]'))) print(a.text) except (NoSuchElementException, StaleElementReferenceException, TimeoutException) as e: print('fail')
补充注意事项
- 确保你导入的
TimeoutException来源为selenium.common.exceptions,如果误导入asyncio.TimeoutError、HTTP请求库的同名超时异常,会因为异常类型不匹配出现捕获失败的问题。 - 若不需要细分异常类型,也可以直接捕获Selenium异常的父类
WebDriverException,但不推荐这种写法,容易掩盖代码本身的逻辑错误。
内容的提问来源于stack exchange,提问作者PythonNoobie
相关产品推荐
相关产品推荐

