如何遍历下拉列表并单击每个选项?获取 StaleElementReferenceException 错误



我正在使用此代码,但我在结果中单击了有限的选项,之后它抛出了下面给出的错误。

我想点击所有选项,但我不明白为什么会发生这种情况。我的下拉列表中有 50 个选项。

select = Select(wait(driver, 35).until(lambda driver: driver.find_element_by_id('BodyContent__company')))
options = select.options
for opt in options:
# for example
print(opt.text)
opt.click()

错误:过时元素引用异常:过时的元素引用: 元素未附加到页面文档(会话信息: 铬=83.0.4103.116(

任何帮助将不胜感激。

每次点击select元素的选项,元素(select(都会更新。这就是为什么StaleElementReferenceException错误 - 元素已更改的原因。

试试这个。确定select后,使用索引单击所有选项。每次单击后,重新识别select以避免过时的元素引用异常。

select = Select(WebDriverWait(driver, 35).until(EC.visibility_of_element_located((By.ID,'BodyContent__company'))))    
for index in range(len(select.options)):
select.select_by_index(index)
select = Select(WebDriverWait(driver, 35).until(EC.visibility_of_element_located((By.ID,'BodyContent__company'))))

您将需要以下导入:

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

最新更新