Selenium selecting a dropdown option with for loop from dictionary

Elteroooo picture Elteroooo · Aug 28, 2012 · Viewed 9.6k times · Source

I have a form with inputs and dropdown lists:

[...]
<select>
<option></option>
<option>Test User 1</option>
<option>Test User 2</option>
</select>
[...]

I pass the values to Selenium as Dictionary:

dict = {'user':'Test User 1', [...]}

And I use a for loop to do this:

for key in dict.keys():
    inputElement = driver.find_element_by_name(key)
    inputElement.clear()
    inputElement.send_keys(dict[key])

It works with all inputs but with the dropdown menu it doesn't work. But it works when I do it without a loop. For example:

inputElement = driver.find_element_by_name('user')
inputElement.clear()
inputElement.send_keys(dict['user'])

or

inputElement = driver.find_element_by_name('user')
inputElement.clear()
inputElement.send_keys('Test User 1')

Answer

jfs picture jfs · Aug 28, 2012
from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id("dropdown_menu"))
select.select_by_visible_text("Test User 1")