How to select a drop-down menu value with Selenium using Python?
Asked Answered
S

18

332

I need to select an element from a drop-down menu.

For example:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

1) First I have to click on it. I do this:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2) After that I have to select the good element, lets say Mango.

I tried to do it with inputElementFruits.send_keys(...) but it did not work.

Superfamily answered 23/10, 2011 at 16:40 Comment(0)
P
179

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

Just find the element and then enumerate the options, selecting the option(s) you want.

Here is an example:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

Petulancy answered 1/11, 2011 at 20:5 Comment(5)
FYI, using Select class makes the problem much easier to solve, see the answer I've posted.Easternmost
What do I do if I am using find_by_id? How do I supply the value then? Also, how do I find the xpath of an element?Anceline
@PrakharMohanSrivastava (and others) to find the XPath, if you have the source highlighted in Chrome dev tools, you can right click on the source, and choose Copy --> XPath to get the full XPath of that element.Onomasiology
And what if I don't have the name of the text? I just want the first element in the menu.Vocal
The Select class linked in @alecxe's answer provides a select_by_index function that seems like it is what you want.Petulancy
E
567

Selenium provides a convenient Select class to work with select -> option constructs:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get('url')

select = Select(driver.find_element_by_id('fruits01'))

# select by visible text
select.select_by_visible_text('Banana')

# select by value 
select.select_by_value('1')

See also:

Easternmost answered 19/2, 2015 at 17:47 Comment(4)
This is a great way to go, and should be the de facto method. However, I will note that you might have to use the more obtuse "xpath" version if the author of the form has not properly setup a select HTML element. If simply using input fields, xpath should work.Propitious
can we find element by xpath instead of by_id? in Select function?Latashalatashia
This does not trigger an input event for me :( I have to do it myself as mentioned here: #2857013Embus
Very nice. This cleaned up some awful hacks I was using.Gunilla
P
179

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

Just find the element and then enumerate the options, selecting the option(s) you want.

Here is an example:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

Petulancy answered 1/11, 2011 at 20:5 Comment(5)
FYI, using Select class makes the problem much easier to solve, see the answer I've posted.Easternmost
What do I do if I am using find_by_id? How do I supply the value then? Also, how do I find the xpath of an element?Anceline
@PrakharMohanSrivastava (and others) to find the XPath, if you have the source highlighted in Chrome dev tools, you can right click on the source, and choose Copy --> XPath to get the full XPath of that element.Onomasiology
And what if I don't have the name of the text? I just want the first element in the menu.Vocal
The Select class linked in @alecxe's answer provides a select_by_index function that seems like it is what you want.Petulancy
B
51

I hope this code will help you.

from selenium.webdriver.support.ui import Select

dropdown element with id

ddelement= Select(driver.find_element_by_id('id_of_element'))

dropdown element with xpath

ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))

dropdown element with css selector

ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))

Selecting 'Banana' from a dropdown

  1. Using the index of dropdown

ddelement.select_by_index(1)

  1. Using the value of dropdown

ddelement.select_by_value('1')

  1. You can use match the text which is displayed in the drop down.

ddelement.select_by_visible_text('Banana')

Buddy answered 2/12, 2019 at 19:47 Comment(2)
Is there a way to make it into a single code line? rather than making a variable to then apply the Select? ThanksToile
you can write a single line code like this. Select(driver.find_element_by_id('id_of_element')).select_by_index(1)Buddy
J
32

firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
Joubert answered 23/11, 2017 at 13:0 Comment(0)
P
18

As per the HTML provided:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

To select an <option> element from a menu you have to use the Select Class. Moreover, as you have to interact with the you have to induce WebDriverWait for the element_to_be_clickable().

To select the <option> with text as Mango from the you can use you can use either of the following Locator Strategies:

  • Using ID attribute and select_by_visible_text() method:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import Select
    
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
    select.select_by_visible_text("Mango")
    
  • Using CSS-SELECTOR and select_by_value() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
    select.select_by_value("2")
    
  • Using XPATH and select_by_index() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))
    select.select_by_index(2)
    
Pituri answered 5/7, 2020 at 0:14 Comment(0)
O
9

I tried a lot many things, but my drop down was inside a table and I was not able to perform a simple select operation. Only the below solution worked. Here I am highlighting drop down elem and pressing down arrow until getting the desired value -

#identify the drop down element
elem = browser.find_element_by_name(objectVal)
for option in elem.find_elements_by_tag_name('option'):
    if option.text == value:
        break
        
    else:
        ARROW_DOWN = u'\ue015'
        elem.send_keys(ARROW_DOWN)
Onofredo answered 24/11, 2016 at 6:55 Comment(0)
A
6

You don't have to click anything. Use find by xpath or whatever you choose and then use send keys

For your example: HTML:

<select id="fruits01" class="select" name="fruits">
    <option value="0">Choose your fruits:</option>
    <option value="1">Banana</option>
    <option value="2">Mango</option>
</select>

Python:

fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
fruit_field.send_keys("Mango")

That's it.

Acanthocephalan answered 20/11, 2018 at 20:50 Comment(0)
D
5

You can use a css selector combination a well

driver.find_element_by_css_selector("#fruits01 [value='1']").click()

Change the 1 in the attribute = value css selector to the value corresponding with the desired fruit.

Dittany answered 19/3, 2019 at 8:39 Comment(0)
C
5

In this way you can select all the options in any dropdowns.

driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")

print( "The title is  : " + driver.title)

inputs = Select(driver.find_element_by_css_selector('#year'))

input1 = len(inputs.options)

for items in range(input1):

    inputs.select_by_index(items)
    time.sleep(1)
Camarillo answered 20/4, 2020 at 15:20 Comment(2)
I'm trying to select one by one using for items in range(1,input1): inputs.select_by_index(items) , but it starts from the second index. How can I get the first value?Kremer
I think you should start your loop from 0.Hopefully it will not escape first option.Camarillo
C
3

After going through a lot of posts like this one, I managed to figure out a solution that allowed me to select an item in a dropdown. I tried .send_keys, click(), and Select in various ways with no success. Ended up sending the click() command to the dropdown 3 times before clicking on the item in the dropdown.

dropMenu = browser.find_element_by_id('cmbDeviceType')
dropMenu.click()
dropMenu.click()
dropMenu.click()

deviceType = browser.find_element_by_id('cmbDeviceType_DDD_L_LBI16T0')
deviceType.click()

Definitely not super pretty, but it works.

Hope this helps someone. This was done with Python3.7.7 on Firefox 88.0.1.

Centrepiece answered 2/6, 2021 at 19:45 Comment(0)
L
3

Using Following Way You can Select the dropdown value.

select=browser.find_element(by=By.XPATH,value='path to the dropdown')
 select.send_keys("Put value here to select it")
Larousse answered 14/8, 2022 at 18:29 Comment(1)
The code change looks somewhat subtle here. I note that the xpath lookup has changed, as well as the click being removed. The click() being called before assigning the variable may well have been an issue in the original code, but is it a combination of all 3 of these changes that gets it working? Can you edit the post to explain what each change to the code has achieved to help us understand what this answer is doing?Erzurum
E
1

It works with option value:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()
Ene answered 16/6, 2019 at 18:34 Comment(0)
D
1

I use this for all of my clicks and selecting and it always works. For a dropdown item just make sure the xpath is the actual value you want to select.

var = WebDriverWait(driver, explicit_wait_seconds).until(
        EC.element_to_be_clickable((By.XPATH, self)))
    # added the click here.
    ActionChains(driver).move_to_element(var).click()
    perform_actions()

actions.perform()
 # Reset was required to clear it. Might be patched now.
actions.reset_actions()
for device in actions.w3c_actions.devices:
    device.clear_actions()
Dungaree answered 16/2, 2022 at 20:28 Comment(0)
M
0
from selenium.webdriver.support.ui import Select
driver = webdriver.Ie(".\\IEDriverServer.exe")
driver.get("https://test.com")
select = Select(driver.find_element_by_xpath("""//input[@name='n_name']"""))
select.select_by_index(2)

It will work fine

Morphophoneme answered 12/4, 2017 at 13:8 Comment(1)
Doesn't add anything to previous answers.Odontograph
F
0

Dropdown WITHOUT <select>

This works for me every time I face a dropdown without <select> tags

# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")

Import ActionChains module

from selenium.webdriver.common.action_chains import ActionChains

Use ActionChains to click on the element

drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
action = ActionChains(driver)
action.click(on_element=drp_element).perform()
Flanna answered 14/4, 2021 at 12:23 Comment(0)
D
-1

The best way to use selenium.webdriver.support.ui.Select class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.

In this type of situation you can also prefer as alternate solution using execute_script() as below :-

option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")

#now use this to select option from dropdown by visible text 
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);
Disjuncture answered 28/8, 2016 at 13:42 Comment(0)
B
-1
dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')
Bailes answered 21/9, 2021 at 8:25 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Silvan
H
-4
  1. List item
public class ListBoxMultiple {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("file:///C:/Users/Amitabh/Desktop/hotel2.html");//open the website
        driver.manage().window().maximize();
        
        
        WebElement hotel = driver.findElement(By.id("maarya"));//get the element
        
        Select sel=new Select(hotel);//for handling list box
        //isMultiple
        if(sel.isMultiple()){
            System.out.println("it is multi select list");
        }
        else{
            System.out.println("it is single select list");
        }
        //select option
        sel.selectByIndex(1);// you can select by index values
        sel.selectByValue("p");//you can select by value
        sel.selectByVisibleText("Fish");// you can also select by visible text of the options
        //deselect option but this is possible only in case of multiple lists
        Thread.sleep(1000);
        sel.deselectByIndex(1);
        sel.deselectAll();
        
        //getOptions
        List<WebElement> options = sel.getOptions();
        
        int count=options.size();
        System.out.println("Total options: "+count);
        
        for(WebElement opt:options){ // getting text of every elements
            String text=opt.getText();
            System.out.println(text);
            }
        
        //select all options
        for(int i=0;i<count;i++){
            sel.selectByIndex(i);
            Thread.sleep(1000);
        }
        
        driver.quit();

    }

}
Harmonious answered 11/1, 2019 at 10:36 Comment(2)
The question clearly asks for a Python solution, your answer is highly appreciated, but isn't required in this context as it's written in Java.Doorjamb
Sorry but this is not Python as mentioned in the question and in the tagsFeatherbrain

© 2022 - 2024 — McMap. All rights reserved.