Selenium selecting a dropdown option with for loop from dictionary
Asked Answered
P

3

7

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')
Phenanthrene answered 28/8, 2012 at 17:8 Comment(0)
H
13
from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id("dropdown_menu"))
select.select_by_visible_text("Test User 1")
Hildebrandt answered 28/8, 2012 at 17:25 Comment(0)
D
1

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.

Dextroamphetamine answered 28/8, 2012 at 17:19 Comment(2)
driver.implicit_wait() and/or ui.WebDriverWait might be more preferable than time.sleep()Hildebrandt
it didn't work .. the clear() methode is causing this problem! is there a way to do something like this if is_not_dropdown() then input.clear() ?Phenanthrene
F
0

If clear() itself causing the problem means then just include like this. if key != 'user' You cant check by is_not_dropdown() like that since you are doing this in the loop and also the values are in the dictionary.

Festival answered 29/8, 2012 at 11:45 Comment(1)
its a class and i want to use make it apply for all cases ::Phenanthrene

© 2022 - 2024 — McMap. All rights reserved.