无法选择Selenium依赖型下拉选项,报StaleElementReferenceException错误求助
解决下拉框依赖导致的StaleElementReferenceException错误
问题场景
页面存在两个关联下拉框,选择第一个下拉框的REGISTRATION选项后,尝试选择第二个下拉框时触发StaleElementReferenceException错误。测试页面:https://tgtransport.net/TGCFSTONLINE/reports/applicationstatussearch.aspx
原测试代码
# select registration from first dropdown select_item = driver.find_element(By.XPATH, '//*[@id="ctl00_OnlineContent_ddlModule"]') select = Select(select_item) reg_element = driver.find_element(By.CSS_SELECTOR, '#ctl00_OnlineContent_ddlModule > option:nth-child(2)') select.select_by_visible_text('REGISTRATION') assert reg_element.is_selected() try: myElem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ctl00_OnlineContent_ddlInput"]/option[3]'))) print("Page is ready!") except TimeoutException: print("Loading took too much time!") # select registration no from second dropdown driver.find_element(By.XPATH, '/html/body/form/table[2]/tbody/tr[1]/td/div[2]/div/table/tbody/tr[3]/td[2]/select/option[3]').click() driver.find_element(By.ID, "ctl00_OnlineContent_txtInput").click() driver.find_element(By.ID, "ctl00_OnlineContent_txtInput").send_keys("TS07JS1701")
报错信息
Traceback (most recent call last): File "C:\Users\Sonu\PycharmProjects\pythonProject\main.py", line 86, in <module> driver.find_element(By.XPATH, '/html/body/form/table[2]/tbody/tr[1]/td/div[2]/div/table/tbody/tr[3]/td[2]/select/option[3]').click() selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
问题原因
- 选择第一个下拉框后,第二个下拉框的DOM会被重新渲染(动态加载关联选项),原有的元素引用直接失效
- 使用绝对XPATH定位元素,页面结构微小变化就会导致定位失败
- 等待逻辑仅判断元素存在,但元素可能还未完全加载完成、无法交互
解决方案
修改代码,使用Select类处理第二个下拉框,替换等待逻辑为等待元素可交互,改用稳定的定位方式:
from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException # 选择第一个下拉框的REGISTRATION选项 first_dropdown = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "ctl00_OnlineContent_ddlModule")) ) select_first = Select(first_dropdown) select_first.select_by_visible_text('REGISTRATION') # 等待第二个下拉框加载完成并可交互,再进行选择 second_dropdown = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "ctl00_OnlineContent_ddlInput")) ) select_second = Select(second_dropdown) # 替换为你需要选择的选项可见文本,示例为"Registration No" select_second.select_by_visible_text("Registration No") # 输入内容 input_box = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "ctl00_OnlineContent_txtInput")) ) input_box.send_keys("TS07JS1701")
关键修改点
- 对两个下拉框都使用
WebDriverWait等待元素可交互,确保DOM渲染完成 - 用ID定位下拉框(最稳定的定位方式之一),再通过
Select类操作,避免直接定位选项元素 - 选择选项时使用
select_by_visible_text,不依赖选项的索引(索引可能随动态加载变化) - 输入框也添加等待逻辑,确保元素可交互后再输入
内容的提问来源于stack exchange,提问作者S Sahoo
相关产品推荐
相关产品推荐

