Seb_ISU Seb_ISU - 2 months ago 6
Python Question

Looping over option menu selenium in 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()


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

Thank you.

Answer

This should work for you. The code will

  • Find the element
  • Iterate to get all the options from the dropdown
  • Iterate through the list
  • For each item in the list, select the current option
  • It's necessary to re-select the dropdown on each pass, as the web page has changed

Like so:

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)