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>
</select>

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(By.id(“citySelect”));
Select dropdown= new Select(CitySelection);

Another method is directly you can pass in WebElement as below

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

1.2 Select an Option

You can select drodown options by three ways

1.selectByVisibleText(String)
2.selectByIndex(int)
3.selectByValue(String)

2.1 selectByVisibleText:

You can select dropdown value by matching visible text as below

dropdown.selectByVisibleText(“Hyderabad”)

2.2 selectByIndex:

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

dropdown.selectByIndex(2)

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

drodown.selectByValue("option2")
dropdown.selectByValue("option1")

3.Complete Selenium Webdriver Code as follows:

WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);
dropdown.selectByIndex(2);
dropdown.selectByValue("option1");
dropdown.selectByVisibleText("Hyderabad");
ALSO READ  Selenium Introduction

Rajesh K