Reputation: 66
I've made a small code whose purpose is to log me into a website and among select an option in a dropdown menu among other things. And I am unable to figure out how to do this.
I'm using selenium with python and things are working excellent except this piece of code about the dropdown menu:
# dropdown
element = browser.find_element_by_id("rating")
for option in element.find_elements_by_tag_name("option"):
if option.text == "It's OK":
option.click()
break
This is the html code of the page regarding the dropdown menu:
<select name="rating" id="rating" size="1" style="margin-bottom:6px;">
<option value=""></option>
<option value="5">I Love it!</option>
<option value="4">I Like it</option>
<option value="3">It's OK</option>
<option value="2">I Don't like it</option>
<option value="1">I Hate it!</option>
</select>
With this code no error is displayed just it doesn't select anything.
I've also tried the Select function with:
find_element_by_css_selector("select#rating > option[value='2']").click()
But this throwing this error:
NameError: name 'find_element_by_css_selector' is not defined
Upvotes: 4
Views: 6919
Reputation: 5347
Please try the following and let me know. This will click the parent element first, so that, list of values will be displayed on the page and then click on the options.
element= browser.find_element_by_id("rating")
element.click()
for option in element.find_elements_by_tag_name("option"):
if option.text == "It's OK":
option.click()
break
Upvotes: 0
Reputation: 2157
I setup a quick page to test this and it worked!!!
Here is the updated code.
#!/usr/bin/env python3
from selenium import webdriver
browser = webdriver.Firefox()
site = browser.get('http://localhost:8000/')
element = browser.find_element_by_id("rating")
for option in element.find_elements_by_tag_name("option"):
print(option.text)
if option.text == "It's OK":
option.click()
print('fount it!!!')
break
I Love it!
I Like it
It's OK
fount it!!!
My output.
Upvotes: 2
Reputation: 3329
For select tag you need to use below approach to select a option
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('rating'))
select.select_by_index("3")
// or
select.select_by_visible_text("It's OK")
// or
select.select_by_value("3")
Let me know if having any issue
Upvotes: 9