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

Python Selenium遍历下拉框选项时触发StaleElementReferenceException错误求助

StaleElementReferenceException 解决方法:下拉框切换页面后元素失效

错误原因

切换下拉框选项后,页面会重新渲染DOM结构,你提前获取的select元素和options列表会与当前页面的元素脱离关联,后续操作时就会抛出StaleElementReferenceException。

修复代码

需要在每次循环中重新定位下拉框元素,而非复用初始获取的select对象。修改后的代码如下:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome('C:\ProgramData\Anaconda3\chromedriver.exe')
driver.get('https://cvmweb.cvm.gov.br/SWB/Sistemas/SCW/CPublica/InfDiario/CPublicaInfDiario.aspx?PK_PARTIC=121145&SemFrame=')

# 先获取总选项数,减少重复查询次数
select = Select(driver.find_element(By.XPATH,'/html/body/form/table[1]/tbody/tr[1]/td/select'))
total_options = len(select.options)

for index in range(total_options):
    print(index)
    time.sleep(10)
    # 每次循环重新定位下拉框,确保元素关联当前DOM
    select = Select(driver.find_element(By.XPATH,'/html/body/form/table[1]/tbody/tr[1]/td/select'))
    select.select_by_index(index)
    time.sleep(5)
    # 在此处添加你获取当前页面数据的代码

额外优化建议

  • 避免使用绝对XPATH(/html/body/...),改用更稳定的定位方式,比如元素的id、name属性或相对路径,降低页面结构变动导致的定位失败概率。
  • 替换固定的time.sleep()为Selenium的显式等待(WebDriverWait),等待元素可交互后再执行操作,提升代码稳定性和执行效率。

内容的提问来源于stack exchange,提问作者João Weckerle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:05:13