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

如何通过ignored_exceptions规避Selenium中的StaleElementReferenceException?

解决方案:解决Selenium中的StaleElementReferenceException问题

你的核心问题在于:原代码等待元素存在后,又重新查找元素,此时页面可能因字段填写操作发生了DOM更新,新查找的元素看似ID相同,实则是新的DOM节点,导致旧引用失效;同时presence_of_element_located仅保证元素存在,不确保它处于可点击状态。

优化方案1:使用element_to_be_clickable显式等待并直接点击返回的元素

这个条件会同时验证元素存在、可见且可点击,WebDriverWait内部会自动重试处理StaleElementReferenceException等临时异常,无需手动忽略:

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

# 等待元素可点击,直接使用返回的有效元素引用点击
next_button = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.ID, 'c8'))
)
next_button.click()

优化方案2:自定义重试点击函数(应对极端DOM频繁更新场景)

如果页面DOM更新非常频繁,可封装一个带重试逻辑的点击函数,专门处理StaleElementReferenceException:

import time
from selenium.common.exceptions import StaleElementReferenceException, 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 click_with_retry(driver, locator, timeout=30):
    end_time = time.time() + timeout
    while time.time() < end_time:
        try:
            element = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable(locator)
            )
            element.click()
            return
        except StaleElementReferenceException:
            # 元素失效,继续重试
            continue
    raise TimeoutException("元素点击超时")

# 调用示例
click_with_retry(driver, (By.ID, 'c8'))

为什么原代码无效?

  1. 你等待元素存在后,又调用driver.find_element重新查找,此时页面可能已完成DOM更新,新元素和之前等待的元素不是同一个节点,触发StaleElementReferenceException。
  2. presence_of_element_located不验证元素的可点击状态,即使元素存在,也可能处于不可点击状态(比如被覆盖、未渲染完成)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:27:25