【问题标题】:Looping over option menu selenium in python在python中循环选项菜单硒
【发布时间】:2014-03-08 15:41:57
【问题描述】:

我的代码使用 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()

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

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

这不起作用。关于如何让这样的循环工作的任何建议?我对 python 中的循环有什么不明白的地方?

谢谢。

【问题讨论】:

    标签: python loops selenium


    【解决方案1】:

    这应该适合你。代码将

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

    像这样:

    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)
    

    【讨论】:

    • 谢谢,我今晚有时间试试这个。我会确保将此问题标记为已回答。
    • 上面的答案经过几个小修正后有效。 “/option[text()='option1'” 应该在它出现的两个地方删除,“self.br.find_element_by_xpath”应该是“browser.find_element_by_xpath”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2018-01-01
    • 2023-03-28
    • 2022-11-23
    • 2020-02-08
    相关资源
    最近更新 更多