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

Selenium WebDriver中TimeoutException未被捕获问题求助

问题分析与解决

你的代码抛出TimeoutException的原因很明确:WebDriverWait(driver, 10).until(...)这行代码没有被包含在try块中。当等待元素超时的时候,异常直接向外抛出,根本没进入后面的try-except逻辑,自然无法被捕获。

修正后的代码

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def clicking_next_page():
    try:
        # 将等待元素的逻辑移入try块内,超时异常会被捕获
        btn_next_to_click = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='next']")))
        btn_next_to_click.click()
        crawler()
    except TimeoutException:
        # 元素不存在或超时,直接跳过
        pass

额外说明

  • 确保你已经导入了WebDriverWait、EC、By这些必要模块(你的原始代码里没显示这些导入,可能是遗漏了)
  • 如果点击按钮时还可能遇到其他异常(比如元素被遮挡),可以在except里添加对应的异常类型,比如ElementClickInterceptedException,避免程序意外终止

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:07:11