How to Select a Dropdown in Selenium WebDriver using Java

How to Select a Dropdown in Selenium WebDriver using Java

How to select a drop down values using Selenium WebDriver, we have to create a Select an element and will not use the default Web Elements provided by Selenium Webdriver. Let’s consider below drop-down example to select a value using Selenium WebDriver.

Selenium-Testng examples to execute multiple classes
Send Extent Reports in Email with screenshots
Generate HTML Reports using Selenium.
How to write Test Cases PASS or FAIL in Excel using Selenium
Pass webdriver instance to multiple classes

1.HTML Dropdown Code:

<select id="citySelect">
<option value="option1">Ahmedabad</option>
<option value="option2">Hyderabad</option>
<option value="option3">Mumbai</option>
<option value="option4">Pune</option>

1.1 Identify the HTML Element to Select value

Selenium WebDriver providing WebElement class to  identify the or store web element as below

WebElement CitySelection = driver.findElement(“citySelect”));
Select dropdown= new Select(CitySelection);

Another method is directly you can pass in WebElement as below

Select dropdown = new Select(driver.findElement(“citySelect”)));

1.2 Select an Option

You can select drodown options by three ways


2.1 selectByVisibleText:

You can select dropdown value by matching visible text as below


2.2 selectByIndex:

You can select the dropDown value by index attribute of an element as below


index =1 means Ahmedabad
index=2 means Hyderabad

2.3 selectByValue:

You can select dropDown value by Optioon Value in above HTML code we've used multiple options 1,2,3,4 and code will be


3.Complete Selenium Webdriver Code as follows:

WebElement CitySelection = driver.findElement("citySelect"));
Select dropdown= new Select(CitySelection);
ALSO READ  Count number of links in a webpage using Selenium

Rajesh K