在python中循环遍历选项菜单硒 [英] Looping over option menu selenium in python

查看:161
本文介绍了在python中循环遍历选项菜单硒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My code uses selenium to go select options from a drop down menu. I have a code that looks just like this:

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()

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

This works just fine. But there are many options in the drop down menu and I wish to loop over all items in the drop down menu. I prepared the following code to loop over the options:

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

这不起作用.关于如何使这样的循环工作的任何建议?我不了解python中的循环吗?

This does not work. Any suggestion on how to get such a loop to work? Something I do not understand about loops in python?

谢谢.

推荐答案

这应该对您有用.该代码将

This should work for you. The code will

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

像这样:

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)

这篇关于在python中循环遍历选项菜单硒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆