Basic Selenium

How to Handle Dropdown in Selenium webdriver

Hello, Guys, Welcome to Selenium tutorial, today in this post we will see how to handle Dropdown in Selenium webdriver.

Generally, while working with the script we have to select some values from the dropdown and do other activity and validate. The dropdown is just like simple WebElement like Checkbox, textbox etc.

 

Before moving to Dropdown in Selenium webdriver check out few useful posts that will help you while writing scripts.

Dynamic XPath in Selenium

Xpath Plugin for Chrome and ChroPath for Chrome for XPath

 

Please refer the video for the same.

 

 

 

 

Dropdown in Selenium webdriver

Select values from Dropdown in Selenium webdriver

For handling dropdowns, Selenium already provides Select class that has some predefined method which help is a lot while working with Dropdown.

Select class can be find in below package.

org.openqa.selenium.support.ui.Select

 

Select values Dropdown in Selenium webdriver

Let’s Discuss some of the methods and will see the detailed program as well.

  • Select value using Index.

WebElement month_dropdown=driver.findElement(By.id(“month”));

Select month=new Select(month_dropdown);

 month.selectByIndex(4);

Explanation- Here selectbyIndex(int) is method which accept integer as argument so depends on index it will select values. If you give index as 4, it will select 5th value.

Note- Index will start from 0.

 

  • Select value using value attribute.
WebElement month_dropdown=driver.findElement(By.id("month"));

 Select month=new Select(month_dropdown);

 month.selectByValue(“5”);

Explanation- Here selectByValue(String) is a method which accepts values it means whatever value you have in your dropdown. Please refer below screenshot to see how to get values from the dropdown.

In our example we have taken value as 5 it means it will select May from dropdown.

 

  • Select value from Visible text
WebElement month_dropdown=driver.findElement(By.id("month"));

 Select month=new Select(month_dropdown);

 month.selectByVisibleText("Aug");

Explanation- We can also select the value from the text as well. This is very straight forward that whatever text we are passing it simply select that value.

Note- This is case sensitive it means if I pass Aug and dropdown has aug then Selenium will not be able to select value and it will fail your program so make sure Text which you are passing is correct.

In the above example, I am passing Aug in the argument so it will select aug from the dropdown.

 

  • Get Selected option from Dropdown.
WebElement month_dropdown=driver.findElement(By.id("month"));

 Select month=new Select(month_dropdown);

 WebElement first_value=month.getFirstSelectedOption();

 String value=first_value.getText();

Explanation- Here getFirstSelectedOption() will return the first selected option and will return you the WebElement then you can use getText() method to extract text and validate the same based on your requirement

 

  • Get All option from dropdown
WebElement month_dropdown=driver.findElement(By.id("month"));

Select month=new Select(month_dropdown);

List<WebElement> dropdown=month.getOptions();

 for(int i=0;i<dropdown.size();i++){

 String drop_down_values=dropdown.get(i).getText();

 System.out.println("dropdown values are "+drop_down_values);

 }

Explanation- getOptions() is a method of Select class which will return List of WebElement then we can iterate using for loop or iterator and using getText() method we can extract values.

I have another very useful video which will show you how you can handle dropdown which does not have any Select class as well.

This is called BootStrap Dropdown and you can handle them using the findElements method. I have created a video for the same.

Hope you have enjoyed the article and videos. If yes then do share with your friends and let me know if any help required from my side.

More updates Learn Automation page

For any query join Selenium group- Selenium Group

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

66 thoughts on “How to Handle Dropdown in Selenium webdriver

  1. padma kacham says:

    How to write a code for div tags of drop down

    1. Hi Padma,

      You can use the approach mentioned in https://vistasadprojects.com/mukeshotwani-blogs-v2/handle-bootstrap-dropdown-in-selenium-webdriver/. Select class from Selenium will work whenever

  2. Revathi says:

    Hi Mukesh,

    How to select the value (string) from drop down list using selenium.
    I used “Selectfromdropdownbyvalue”. but it fails.kindly help me

    1. Hi Revathi,

      Are you sure that you are dealing with the

  3. Vishal Gupta says:

    Hi , mukesh i am getting Element could not be scrolled into view exception, i dont know how to use scrolling inside a select tag i have tried and searched so much on internet but not getting exactly what i want, my drop down contains a scroll option .

    1. Hey Vishal, can you please share your code so that I can guide you?

  4. Parth says:

    Hello admin i got this error in eclipse console
    “Element should have been “select” but was “div””

    Here below is my code for dropdownlist (i used xpath because there is nothing show in element)
    WebElement location = driver.findElement(By.xpath(“//*[@id=\”WorkOrderModal_outlet_id\”]/div/div/div[1]”));
    Select locations = new Select(location);
    locations.selectByIndex(2);
    }

    1. Hi Parth,

      Select class only works when you have dropdown with Select tag. If you have any other tag then follow the below approach. I have a detailed video on this too https://vistasadprojects.com/mukeshotwani-blogs-v2/handle-bootstrap-dropdown-in-selenium-webdriver/

  5. Chetan Sonawane says:

    Hi Mukesh,

    I have a scenario where few more options are added in the country dropdown like (added 10 more countries), Could you please help me how to verify that newly added options are available in the dropdown ?

    Your help is much appreciated !!

    Thanks in advanced 🙂

    1. Hi Chetan,

      Once you get getAllOptions from dropdown in a list, verify new values being added.

  6. Ranjeet says:

    hai Mukesh ,i want to print the value of the selected option by index from drpdown

    1. Hi Ranjeet,

      Use selectClassObject.getFirstSelectedOption().getText() and this returns String which you can print on console using sysout.

  7. dee says:

    we can also make use of the for loop in below way,

    //monthdropdown handling
    WebElement month_dropdown = driver.findElement(By.id(“month”));
    Select month_dd=new Select(month_dropdown);

    //fetching total no.of options present in dropdown
    List getvaluesmonth_dd=month_dd.getOptions();

    //printing total no using size()
    int totalvaluesinmonth_dd=getvaluesmonth_dd.size();
    System.out.println(“total options in month dropdown is “+totalvaluesinmonth_dd);

    for(int i=0;i<getvaluesmonth_dd.size();i++){
    System.out.println(getvaluesmonth_dd.get(i).getText());
    }

    1. Hi Dee,

      This way also it works…:)

  8. neelu says:

    how to select the option from cascading dropdown in selenium webdriver using java code?

    1. Hi Neelu can you share application URL where I can find cascading dropdown ?

  9. nayana says:

    hi
    could please help me as I have to prepare an interview as an automation tester.
    please advise which part need to more focus.

  10. Rahul says:

    The chrome driver clicks on the wrong element when the browser zoom level is not set to 100%, how can i solve this issue ?

    1. Hi Rahul,

      Its always recommendable to have 100% zoom setting for all browsers while using Selenium. There is a limitation for this. Please check this Chromium Bug where same bug has been posted log back into chromium project

  11. Saiprasad says:

    Hi Mukesh,

    How to do the select values from an excel. Suppose that i am writing a code for a form for which i am taking values from an excel. Now how to deal with select method. How to write a program for select method which would select a value based on the excel data

    1. Hi Sai,

      Whatever value you want to set in drop down, read same data from excel. You just need to pass value from excel as argument to method which contains select operation.

  12. sucheta says:

    How to select element from drop down for label class

    1. Hi Sucheta,

      If there is no select tag then obviously Selenium won’t provide native support for such kind of drop down. You need to come up with your custom way to handle such kind of control. You can refer this link for better understanding https://vistasadprojects.com/mukeshotwani-blogs-v2/handle-bootstrap-dropdown-in-selenium-webdriver/

  13. Chedomil says:

    Hello Mukesh,
    How can I select last value in in dropdown, when I do not know final index?
    This option would be perfect, but…
    abc.selectByIndex(max index)
    or
    abc.selectByValue(contains “something”)
    abc.getLastSelectedOption 🙂
    Do you have any advice about this?

    1. Hi Chedomil,

      You can call getAllOptions().size()-1 which will always select last value from Dropdown.

      1. Bapaiah says:

        HI Mukesh’

        it’s getoptions().size()-1 or getAllOptions().size()-1 .. pls correctme

        1. Hi Bapaiah,

          As per selenium documentation,
          getOptions Returns: List of all options belonging to this select tag
          getAllSelectedOptions Returns: List
          of all selected options belonging to select tag

  14. anita says:

    hi
    how to read first element from dropdown

    1. Hi Anita,

      Use getOptions(), this returns list of WebElements. Then you can get first index followed by getText() to fetch exact value which you can see in webpage.

  15. Srihari Babu Anaparthi says:

    Hi Mukesh,

    I am trying to select dropdown value using selectByVisiabletext option but it is not working IE9 Browser.Could you pls help me.

    Thanks,
    Srihari

    1. Hi Srihari,

      First please share an executable scenario and a sample page to look into this issue.

  16. Armands says:

    Hi Mukesh,
    Hi Anil,

    I face to problem. When the dropdown tag element is not a ‘select’ but a ‘button’

    1. Hi Armands,

      Selenium by default supports only select tag. If you are seeing other than select then you need to go for some workaround.

  17. Dhanalakshmi says:

    Hi mukesh ,
    I have error in my code..
    plz resolve it

    FirefoxDriver driver=new FirefoxDriver();
    driver.get(“http://www.gmail.com”);

    File srcFile= driver.getScreenshotAs(OutputType.FILE);
    File destFile= new File(“D://image.png”);
    FileUtils.copyFile(srcFile, destFile);

  18. Dhanalakshmi says:

    Hi Mukesh,
    Im getting error in this code. plz resolve it.
    FirefoxDriver driver=new FirefoxDriver();
    driver.get(“http://www.airindia.com”);
    Select select=new Select(driver.findElement(By.xpath(“.//*[@id=’_classType1′]”))Select.selectByValue(3));

    1. Hi,

      use selectByIndex(3)

  19. Priyanka D. says:

    Hi Mukesh,

    Plz help me on how to handle auto complete text boxes.

  20. anusha says:

    how to perform click automation in dropdown one by one in selenium webdriver

    1. Hey Anusha,

      You have 2 options to do this. You can get all dropdown using by tagname and then run a for loop to handle this.

      I have also recorded the video for another kind of dropdown which will give you clear picture.

  21. Arjun says:

    how to perform actions on already opened browser

    1. Hi Arjun,

      Selenium always starts with fresh session so you can’t perform operation on opened browser.

  22. Radik says:

    Hi Mukesh,
    Thanks you so much for your excellent tutorial.

    I wanted to ask how can I convert WebElement to string so I can use array list?
    I want to solve your assignment.
    Please assist.

    Thanks
    Radik

    1. Hey Radik,

      What is the need to converting WebElement to String?

  23. RC says:

    Hi.

    I dont know what i am doing wrong. but my select is not working. iv tried facebook and many other demo sites. need help plz

    RC

    1. Hi Rupika,

      Can you send me your script to mukeshotwani@learn-automation.com I will check and reply.

    2. kashsih says:

      hey even i am facing the same error. did u find out fault in ur code. kindly let me know

      1. Hi Kashish,

        Are you running your script from cmd?

  24. Abhinav says:

    Hi Mukesh

    I think the index does not start from 0. As I gave the index 2 and Feb got selected.
    Please cross check.

    1. Hi Abhinav,

      It starts with zero, In this case zero index points to month text

  25. Somanath says:

    hi Mukesh,
    how to store the expected values in arrayList and then how will using the assersion for this ArrayList

    1. Hi Somanath this is my next post will update soon.

  26. shabana banu says:

    Hi Mukesh

    I like your article and I am following it, but I am stuck with div class. I dont know how to select the item from div class drop down, please help me out.

    Thanks
    Shabana

  27. Raju Raipure says:

    Hi Mukesh,
    I have a drop down option which displays the options on mouse over. I want o get all the options available under the drop down. Can you please suggest how can I do it?
    Thanks

    1. Hi Raju, any sample app?

  28. pavani says:

    hi mukesh,

    If we are using drop down but having div class instead of select class what needs to be done

    1. Hi Pavani,

      In this case you can use findElements() method which will return list of elements then you can select the item.

  29. Amit Chaudhary says:

    Hi Mukesh,

    Thanks for your reply. My code is working fine now, i messed up with index value in my code.

    But now i have another problem related to radio buttons, there is page on which only 2 radio buttons are visible on application and 2 radio are hidden, but i want to select the first visible radio button. Is there any way i can do this ?

    below are steps you use to create a scenario-
    open link – https://www.fedex.com/ratefinder/home?cc=US&language=en&locId=express
    select *No. of packages as ‘2’ under additional information section
    here i want to select first radio button based on index rather than any other attribute.

    Thanks,
    Amit Chaudhary

    1. Hi Amit,

      Dynamic xpath will help you check dynamic xpath video in Youtube.

    2. Atul gupta says:

      Hi Mukesh,

      I have seen you all videos. All are very helpful to me and i am enhancing my skill through this all.

      today i have a query now that If we have multiple dropdown and all dropdown is depend on previous one selection dropdown. How we will execute second one or how to write the script in webdriver.

      Ex:- one dropdrown for Mobile Brand name
      Second dropdown for Mobile Model so mobile model name depend on Brand name.
      Can you provide me solution as soon as possible please.

      Regard.

      Atul gupta

      1. Hi Atul,

        Thanks for nice feedback 🙂 I generally use explicit wait to handle this scenario.

  30. Amit Chaudhary says:

    Hi Mukesh,

    i’m trying to trying to perform select operation on a dropdown using index of the element. Something like this –

    For Example, here i’m writing below code to select some values from any dropdown from a page using index. But below code is not working, Can you please help me on this ?

    List el = driver.findElements(By.tagName(“select”));

    Select select = new Select(el.get(index));
    select.selectByVisibleText(value);

    1. Hi Amit,

      Which app you are automating?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.