In this tutorial we will learn How to Handle Drop-down in Selenium webdriver and number of ways to handle drop-down in selenium.
What is Drop-down?
Drop-down is a list of items that appear when clicking on a button or text selection. While automating any website or page tester comes across with selectable elements in drop-down list.
So before starting with automating drop-down you can go through to the below image of face book drop-down on its sign up page. I am taking an example of automating this drop-down.
Before controlling drop-down box, we must work on below things, start with package import in selenium webdriver:
Import the package: org.openqa.selenium.support.ui.Select
Declare the elements by assigning their location by selecting id, class name and xpath. Use below code for declaration:
Select dropdown = new Select(driver.findElement(By.id(“Element ID”)));
Use select methods to handle values in dropdown, refer the below sample code for starting with selection. This method will select the value on index “6”.
Methods for drop-down selection in selenium webdriver:
selectByVisibleText() method will select element in drop-down by giving the text or option in drop-down. This is the simplest method as there is no need to select any id from inspect element.
dropdown.selectByVisibleText(mention text here);
2. selectByValue() selectByValue() method is used to select elementby referring its value, now question arises that how to get the value of drodp down.
— Inspect element by firebug — Select blue color mouse cursor from console
— click on the dropdown and view console. — Click on + icon to fetch value of element in drop down, it will give all id’s of element in drop-down.
This will select element aligned with value = 1.
You can also use selectByIndex() method to make selection in drodp-down, to find index of the element.
— Right click on browser or website and select option “Inspect element with firebug”
— Take blue colored cursor in console on drop-down to be automated.
— view selected code in console at the bottom of the screen