在Python中循环选择菜单硒
问题内容:
我的代码使用硒从下拉菜单中选择选项。我有一个看起来像这样的代码:
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()
这样很好。但是下拉菜单中有很多选项,我希望遍历下拉菜单中的所有项目。我准备了以下代码来遍历选项:
options = ["option1", "option2"]
for opts in options:
browser.find_element_by_xpath("//select[@id='idname']/option[text()=opts]").click()
这是行不通的。关于如何使这样的循环工作的任何建议?我不了解python中的循环吗?
谢谢。
问题答案:
这应该为您工作。该代码将
- 查找元素
- 迭代以从下拉列表中获取所有选项
- 遍历列表
- 对于列表中的每个项目,选择当前选项
- 由于网页已更改,因此必须在每次通过时重新选择下拉菜单
像这样:
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)