Unlike other web elements, we can’t just locate the dropdown object and select a value from it in Selenium WebDriver.In this post, I will show you how to select value from dropdown in Selenium WebDriver and perform additional validations to avoid a Selenium WebDriver runtime exceptions.
First and foremost you will have to understand the prerequisites of handling drop-downs in Selenium WebDriver.
Select Class in Selenium WebDriver to Select value from WebList
The ‘Select‘ Class in Selenium WebDriver is used to select and deselect a value in a dropdown. We have to pass the dropdown WebElement object as a parameter to the Select class constructor to initialize its object.
Syntax:
WebElement DropDownElement = driver.findElement(By.id(“Dropdown1″));
Select dropdownSelectObject = new Select(DropDownElement );
We will consider the following DOM structure for the examples. This is the Facebook Signup popup page.
Automating DropDown in Selenium WebDriver
Select value from the Dropdown in Selenium WebDriver?
There are three possible ways to select an item from the drop-down menu.
- selectByIndex
- selectByValue
- selectByVisibleText
How to select a value from a Dropdown By Using its Index In Selenium?
The selectByIndex() method is used to select an item based on its index. The index of the first item starts from 0.
1 2 3 4 |
//Select fourth option in the dropdown dropdownSelectObject.selectByIndex(3) |
A complete example of all select methods has been given at the end of this article.
How to select a value from a Dropdown By Using its Value attribute In Selenium?
The selectByValue() method is used to select an item by using its ‘value‘ attribute in the Option Tag.
1 2 3 4 |
//Select dropdown item by using value attribute dropdownSelectObject.selectByValue("2") |
Note: It is not necessary that the dropdown item has a value attrubute.If the value attribute is not available this method won’t work.
How to select a value from a dropdown By Using its Visible Text Value In Selenium?
The selectByVisibleText() method is used to select an item from a dropdown based on the items or text values present in the dropdown.
1 2 3 4 5 |
//Select dropdown option by using item present in the dropdown WebElement selectedItem = dropdownSelectObject.getFirstSelectedOption(); String selectedValue = selectedItem.getText()); |
How to Get Selected Value from a Dropdown In Selenium?
Sometimes we have to verify whether we have selected the correct value from the dropdown. To validate the selected value we can get the selected option from the dropdown and compare it with the expected value. You can use the following Selenium Code to get the selected value from the dropdown.
1 2 3 4 5 |
//Get Selected value from a Dropdown WebElement selectedItem = dropdownSelectObject.getFirstSelectedOption(); String strSelectedValue = selectedItem.getText(); |
How to Check whether a DropDown is Visible and Enabled on the Page?
Whenever you are going to perform any action on a web element it is standard practice to first check whether it is visible on the page. If it is visible the next thing we should check whether it is enabled or not. The following example illustrates how to do it. Here we will first check whether the required dropdown is visible on the page using isDisplayed() method. If it is visible we will check whether it is in the enabled state using the isEnabled() method. If it is enabled we will select a value from it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * Validate whether the Dropdown is visible and enabled */ Boolean visibleState =driver.findElement(By.id("month")).isDisplayed(); System.out.println("The Dropdown visibility is: "+visibleState); if(visibleState) { Boolean status =driver.findElement(By.id("month")).isEnabled(); System.out.println("The status of Dropdown is: "+status); //If Dropdown is enabled select desired value if(status) { //write code for selecting desired value } } |
How to Check whether a value exists in a DropDown in Seleneium?
What would happen if you try to select a value from the dropdown but that value does not exist in the dropdown. There could be multiple reasons like you have provided an incorrect value, the values in the dropdown, and that particular value is not loaded in the dropdown. In all such situations, Selenium will throw a runtime exception.
Exception in thread “main” org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
So, it would be a better approach to first check whether the required value exists in the dropdown that you want to select to avoid runtime exceptions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
WebElement DropDownElement=driver.findElement(By.xpath("//select[@id='month']")); //Creating dropdown object for Month dropdown Select dropdownSelectObject=new Select(DropDownElement); //Getting all the items of dropdown List<WebElement> DrpDownList=dropdownSelectObject.getOptions(); //Iterating all the elements of dropdown for(int i=0;i<DrpDownList.size();i++ ) { if(DrpDownList.get(i).getText().equalsIgnoreCase("Jun")) { System.out.println("Required Value exists in the dropdown"); dropdownSelectObject.selectByVisibleText("Jun"); break; } } |
Complete Code Showing all Examples around a Dropdown in Selenium WebDriver
Let’s consider the DOM Structure of the Facebook Signup Page.Test Scenario:
- Launch a new chrome browser
- Open Facebook.com
- Click on the Create New Account Button
- Switch to the Sign Up Pop-up window
- Select Jun month on the Sign-Up popup window
- Verify Jun month has been selected in the dropdown
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class DropDownSelectExample { public static void main(String[] args) throws InterruptedException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Navigating to Facebook driver.get("https://www.facebook.com/"); //Clicking on the Create New Account on Facebook login page driver.findElement(By.id("u_0_2")).click(); //Waiting for Six Seconds Thread.sleep(6000); //Switching to active Pop-up Window driver.switchTo().activeElement(); //Waiting for 5 Seconds to load the pop-up window Thread.sleep(5000); Boolean visibleState =driver.findElement(By.id("month")).isDisplayed(); System.out.println("The Dropdown visibility is: "+visibleState); if(visibleState) { Boolean status =driver.findElement(By.id("month")).isEnabled(); System.out.println("The status of Dropdown is: "+status); //If Dropdown is enabled select desired value if(status) { WebElement DropDownElement=driver.findElement(By.xpath("//select[@id='month']")); //Creating Dropdown object for Month Dropdown Select dropdownSelectObject=new Select(DropDownElement); List<WebElement> DrpDownList=dropdownSelectObject.getOptions(); Boolean flagitem=false; for(int i=0;i<DrpDownList.size();i++ ) { if(DrpDownList.get(i).getText().equalsIgnoreCase("Jun")) { System.out.println("Required Value exists in the dropdown"); dropdownSelectObject.selectByVisibleText("Jun"); //Getting Selected item element WebElement selectedItem = dropdownSelectObject.getFirstSelectedOption(); //Getting the text value of Selected Item String strSelectedValue = selectedItem.getText(); //Comparing the Selected item with the expected value i.e Jun if(strSelectedValue.equalsIgnoreCase("Jun")) { System.out.println("Desired Month Jun is selected in the dropdwon"); flagitem=true; break; } } } if(flagitem==false) { System.out.println("Required Value not found in the dropdown"); } } } //close browser driver.close(); } } |
Conclusion
- We can select a value from a drop-down by initializing the object of the Select class
- We can locate the drop-down elements by id, name, CSS, and XPath selector.
- We can perform validation operations like isDisplayed() and isEnabled() before selecting any value from dropdown to get rid of runtime exceptions thrown by Selenium WebDriver.
Recommended Posts
- Top #23 Most Useful Selenium WebDriver Commands That You Must know
- How to Download and Install Eclipse
- Configure Selenium Webdriver With Eclipse
- How To Install TestNG in Eclipse
- Selenium Webdriver Login Test Script
- How to Select a Radio Button In Selenium WebDriver And Do Other Validations?
- XPath in Selenium WebDriver with Example
- How to Use CSS Selector in Selenium WebDriver | 13 Examples
- What is Selenium WebDriver & its Architecture