How To Handle Dropdown

In this article, we will learn how to handle DropDown in Selenium.

How to Select Option from Drop-Down Box :

To select value from dropdown in selenium, we have to follow the following steps:

Step 1: Import the “Select” package.

import org.openqa.selenium.support.ui.Select;

Step 2: Create web element by using findElement() method

Step 3: Create object of Select Class and pass parameter (webelement)

Select s = new Select(webElement);

Step 4: There are three methods of Select Class
1) s.selectByIndex(int) ;
2) s.selectByValue(String)
3) s.selectByVisibleText(String);
Use any mehod from above to select option from dropdown.

Select Methods:

The most common methods used on Selenium dropdown list are as follows:

1. selectByValue() : This method is used to select the option whose “value” attribute matches the specified parameter. It accepts parameter as the value of the “value” attribute.
Example - drpCar.selectByValue("benz");

2. selectByVisibleText() : This method is used to select the option that displays the text matching the parameter. It accepts parameter as the exactly displayed text of a particular option.
Example - drpCar.selectByVisibleText("Honda");

3. selectByIndex() : This method is used to select the option at the given index. It accepts parameter as the index of the option to be selected. Index starts from 0.
Example - drpCar.selectByIndex(1);

Example:

CODE
 
public class Handle_DropDown {

	public static void main(String[] args) {

		System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Files\\chromedriver.exe");
		
		WebDriver driver = new ChromeDriver();
		
		driver.get("https://courses.letskodeit.com/practice");
		
		driver.manage().window().maximize();
		
		
        // create webelement of dropdown
		WebElement dropdown = driver.findElement(By.xpath("//select[@id=`carselect`]"));
		
        // we have to create object of select class
		Select drpCar = new Select(dropdown);
		
        // we can select option from dropdown by using any of the following three methods
		
		drpCar.selectByIndex(1);                 
		
		   // Or
	
		drpCar.selectByValue("benz");           

		   // Or
	
		drpCar.selectByVisibleText("Honda");   
	}
}	
	
#How_to_handle_dropdown_using_selenium_webdriver #select_methods_ #How_to_handle_dropdown_using_selenium_with_example

(New page will open, for Comment)

Not yet commented...