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.
Xpath Plugin for Chrome and ChroPath for Chrome for XPath
Please refer the video for the same.
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
padma kacham says
How to write a code for div tags of drop down
Mukesh Otwani says
Hi Padma,
You can use the approach mentioned in https://learn-automation.com/handle-bootstrap-dropdown-in-selenium-webdriver/. Select class from Selenium will work whenever
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
Mukesh Otwani says
Hi Revathi,
Are you sure that you are dealing with the
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 .
Mukesh Otwani says
Hey Vishal, can you please share your code so that I can guide you?
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);
}
Mukesh Otwani says
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 http://learn-automation.com/handle-bootstrap-dropdown-in-selenium-webdriver/
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 🙂
Mukesh Otwani says
Hi Chetan,
Once you get getAllOptions from dropdown in a list, verify new values being added.
Ranjeet says
hai Mukesh ,i want to print the value of the selected option by index from drpdown
Mukesh Otwani says
Hi Ranjeet,
Use selectClassObject.getFirstSelectedOption().getText() and this returns String which you can print on console using sysout.
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());
}
Mukesh Otwani says
Hi Dee,
This way also it works…:)
neelu says
how to select the option from cascading dropdown in selenium webdriver using java code?
Mukesh Otwani says
Hi Neelu can you share application URL where I can find cascading dropdown ?
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.
Mukesh Otwani says
Hi Nayana, this will help http://learn-automation.com/selenium-interview-questions-and-answers/
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 ?
Mukesh Otwani says
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
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
Mukesh Otwani says
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.
sucheta says
How to select element from drop down for label class
Mukesh Otwani says
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 http://learn-automation.com/handle-bootstrap-dropdown-in-selenium-webdriver/
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?
Mukesh Otwani says
Hi Chedomil,
You can call getAllOptions().size()-1 which will always select last value from Dropdown.
Bapaiah says
HI Mukesh’
it’s getoptions().size()-1 or getAllOptions().size()-1 .. pls correctme
Mukesh Otwani says
Hi Bapaiah,
As per selenium documentation, of all options belonging to this select tag of all selected options belonging to select tag
getOptions Returns: List
getAllSelectedOptions Returns: List
anita says
hi
how to read first element from dropdown
Mukesh Otwani says
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.
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
Mukesh Otwani says
Hi Srihari,
First please share an executable scenario and a sample page to look into this issue.
Armands says
Hi Mukesh,
Hi Anil,
I face to problem. When the dropdown tag element is not a ‘select’ but a ‘button’
Mukesh Otwani says
Hi Armands,
Selenium by default supports only select tag. If you are seeing other than select then you need to go for some workaround.
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);
Mukesh Otwani says
Hi,
Kindly refer below post for screenshot in Selenium
http://learn-automation.com/how-to-capture-screenshot-in-selenium-webdriver/
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));
Mukesh Otwani says
Hi,
use selectByIndex(3)
Priyanka D. says
Hi Mukesh,
Plz help me on how to handle auto complete text boxes.
Mukesh Otwani says
Hi Priyanka,
Below link will guide you for the same.
http://www.software-testing-tutorials-automation.com/2014/05/how-to-handle-ajax-auto-suggest-drop.html
anusha says
how to perform click automation in dropdown one by one in selenium webdriver
Mukesh Otwani says
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.
Arjun says
how to perform actions on already opened browser
Mukesh Otwani says
Hi Arjun,
Selenium always starts with fresh session so you can’t perform operation on opened browser.
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
Mukesh Otwani says
Hey Radik,
What is the need to converting WebElement to String?
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
Mukesh Otwani says
Hi Rupika,
Can you send me your script to mukeshotwani@learn-automation.com I will check and reply.
kashsih says
hey even i am facing the same error. did u find out fault in ur code. kindly let me know
Mukesh Otwani says
Hi Kashish,
Are you running your script from cmd?
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.
Mukesh Otwani says
Hi Abhinav,
It starts with zero, In this case zero index points to month text
Somanath says
hi Mukesh,
how to store the expected values in arrayList and then how will using the assersion for this ArrayList
Mukesh Otwani says
Hi Somanath this is my next post will update soon.
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
Mukesh Otwani says
Hi Shabana,
Below post covers the same http://selenium-venkat.blogspot.in/2016/02/21-select-month-from-birthday-field-in.html
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
Mukesh Otwani says
Hi Raju, any sample app?
pavani says
hi mukesh,
If we are using drop down but having div class instead of select class what needs to be done
Mukesh Otwani says
Hi Pavani,
In this case you can use findElements() method which will return list of elements then you can select the item.
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
Mukesh Otwani says
Hi Amit,
Dynamic xpath will help you check dynamic xpath video in Youtube.
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
Mukesh Otwani says
Hi Atul,
Thanks for nice feedback 🙂 I generally use explicit wait to handle this scenario.
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);
Mukesh Otwani says
Hi Amit,
Which app you are automating?