Seb_ISU Seb_ISU - 1 month ago 5x
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()

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:

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.


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 import Select, WebDriverWait
browser = webdriver.Firefox()

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

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

    select = Select(browser.find_element_by_xpath( "//select[@id='idname']"))