Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium selecting a dropdown option with for loop from dictionary

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')
like image 542
Elteroooo Avatar asked Aug 28 '12 17:08

Elteroooo


2 Answers

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id("dropdown_menu"))
select.select_by_visible_text("Test User 1")
like image 158
jfs Avatar answered Sep 20 '22 18:09

jfs


If clear() is the issue ... then do the following:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
dict = {'user': 'Test User 1', 'user': 'Test User 2'}
for key in dict.keys():
    inputElement = driver.find_element_by_name(key)
    if inputElement.tag_name == 'input':
        inputElement.clear()
        inputElement.send_keys(dict[key])
    elif inputElement.tag_name == 'select':
        # now use the suggestion by J.F. Sebastian
        select_obj = Select(inputElement)
        select_obj.select_by_visible_text(dict[key])

This works in FF, and it will most likely work in Chrome too, but haven't tested it.

like image 1
Igor Serko Avatar answered Sep 22 '22 18:09

Igor Serko