繁体   English   中英

如何使用 selenium WebDriver python 遍历每个下拉列表

[英]How to traverse each dropdown list using selenium WebDriver python

我的网页结果带有如下 html 标签,我需要循环每个值并从表中获取结果

 <div class = "divList"> <select class="form selectList"> <option value="3710">Thu, 04 Nov 2021</option> <option value="3709">Mon, 01 Nov 2021</option> <option value="3708">Mon, 01 Nov 2021</option> .... </select> </div>

dropdownlist = driver.find_element_by_class_name('divList')
valueslist = (dropdownlist.text).splitlines()
print(valueslist)
sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
for value in valueslist:
   print(value)
   sel.select_by_visible_text(value)
   print('Processing - ', value)
   time.sleep(3)

在 2 次迭代后更改值时出现以下错误

Thu, 04 Nov 2021
Processing -  Thu, 04 Nov 2021
Mon, 01 Nov 2021
Processing -  Mon, 01 Nov 2021
Thu, 28 Oct 2021

selenium.common.exceptions.StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档

尝试这个:

dropdownlist = driver.find_element_by_class_name('divList')
valueslist = (dropdownlist.text).splitlines()
print(valueslist)
sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))

for value in valueslist:
    sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
    sel.select_by_visible_text(value)
    print('Processing - ', value)
    time.sleep(3)

如果您愿意,您可以通过以下方式简化:

sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
nbritems = len(sel.options)
for i in range(0, nbritems):
    sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
    txt = sel.options[i].text
    sel.select_by_visible_text(txt)
    print('Processing - ', txt)
    time.sleep(3)

selenium.common.exceptions.StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档

字面意思是about,引用的元素已经过期,不再附加到当前页面。 通常,这是因为页面被刷新或跳过了,解决方法是,重用 findElement 或 findElements 方法来定位元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM