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

Selenium Python遇StaleElementReferenceException异常求助排查

解决StaleElementReferenceException异常:洗碗机洗涤剂页面数据提取问题

问题分析

你的代码触发StaleElementReferenceException的核心原因:

  • 你将页面中的WebElement对象存入了products列表,点击下一页后页面DOM重新渲染,之前的元素引用会直接失效
  • 每次循环都把当前页的元素追加到products,后续遍历列表时,访问的是已经失效的旧页面元素,必然抛出异常
  • 冗余的time.sleep()和重复定位元素操作,没有解决元素引用失效的根本问题

修正方案

不要存储WebElement对象,直接提取元素的文本内容存入列表;同时优化等待逻辑,确保操作前元素处于可用状态:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:/Users/Lenovo/PycharmProjects/pythonProject/chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

driver.get("https://ec.europa.eu/ecat/category/en/5/dishwasher-detergents")
products = []

num_pages = 7
step = 0

while step < num_pages:
    try:
        # 等待表格行可见,确保元素可操作
        rows = wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@id='producersTableId']/tbody/tr/td[4]")))
        # 直接提取文本存入列表,不保留WebElement引用
        current_page_texts = [row.text for row in rows]
        products.extend(current_page_texts)
        # 打印当前页数据
        for text in current_page_texts:
            print(text)
        
        # 等待下一页按钮可点击并触发跳转
        next_Butt = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='producersTableId_next']/a")))
        driver.execute_script("arguments[0].click();", next_Butt)
        # 等待当前页元素失效,确认页面切换完成
        wait.until(EC.staleness_of(rows[0]))
        step += 1
    except Exception as e:
        print(f"错误信息: {e}")
        continue

print(f"总共提取到 {len(products)} 条数据")
driver.quit()

关键改动说明

  1. 存储文本而非WebElement:通过列表推导式直接提取元素文本,彻底摆脱对DOM元素引用的依赖,从根源避免 stale 异常
  2. 优化等待策略:用visibility_of_all_elements_located确保元素可见后再操作,比presence_of_all_elements_located更贴合实际交互场景
  3. 页面切换验证:用staleness_of等待当前页元素失效,确认页面完成切换后再进入下一轮循环,避免提前定位下一页元素导致的错误
  4. 移除冗余延迟:显式等待已经能保证元素状态,不需要额外固定sleep,提升代码效率和稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:05:53