在python中循环选项菜单selenium

Seb*_*ISU 1 python selenium loops

我的代码使用 selenium 从下拉菜单中选择选项。我有一个看起来像这样的代码:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://www.website.com")
browser.find_element_by_xpath("//select[@id='idname']/option[text()='option1']").click()
Run Code Online (Sandbox Code Playgroud)

这工作得很好。但是下拉菜单中有很多选项,我希望遍历下拉菜单中的所有项目。我准备了以下代码来循环选项:

options = ["option1", "option2"]
for opts in options:
    browser.find_element_by_xpath("//select[@id='idname']/option[text()=opts]").click()
Run Code Online (Sandbox Code Playgroud)

这不起作用。关于如何让这样的循环工作的任何建议?我对 python 中的循环不了解?

谢谢你。

Ric*_*ard 5

这应该对你有用。该代码将

  • 查找元素
  • 迭代以从下拉列表中获取所有选项
  • 遍历列表
  • 对于列表中的每个项目,选择当前选项
  • 有必要在每次通过时重新选择下拉菜单,因为网页已更改

像这样:

from selenium import webdriver
from selenium.webdriver.support.ui import Select, WebDriverWait
browser = webdriver.Firefox()
browser.get("http://www.website.com")

select = browser.find_element_by_xpath( "//select[@id='idname']")  #get the select element            
options = select.find_elements_by_tag_name("option") #get all the options into a list

optionsList = []

for option in options: #iterate over the options, place attribute value in list
    optionsList.append(option.get_attribute("value"))

for optionValue in optionsList:
    print "starting loop on option %s" % optionValue

    select = Select(browser.find_element_by_xpath( "//select[@id='idname']"))
    select.select_by_value(optionValue)
Run Code Online (Sandbox Code Playgroud)