Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Python dropdown find and select doesn't work

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
like image 331
Backup Avatar asked Sep 19 '25 20:09

Backup


1 Answers

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

like image 166
Trimantra Software Solution Avatar answered Sep 22 '25 09:09

Trimantra Software Solution