Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an item from a dropdown list using Selenium WebDriver with java?

People also ask

How do I select a dropdown value in automation?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.


Use -

new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");

Of course, you need to import org.openqa.selenium.support.ui.Select;


Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

dropdown.selectByValue("prog");

Happy Coding :)


Tagname you should mentioned like that "option", if text with space we can use this method it should work.

WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));

for (WebElement option : options) {

if("Germany".equals(option.getText().trim()))

 option.click();   
}

You can use 'Select' class of selenium WebDriver as posted by Maitreya. Sorry, but I'm a bit confused about, for selecting gender from drop down why to compare string with "Germany". Here is the code snippet,

Select gender = new Select(driver.findElement(By.id("gender")));
gender.selectByVisibleText("Male/Female");

Import import org.openqa.selenium.support.ui.Select; after adding the above code. Now gender will be selected which ever you gave ( Male/Female).


Google "select item selenium webdriver" brings up How do I set an option as selected using Selenium WebDriver (selenium 2.0) client in ruby as first result. This is not Java, but you should be able to translate it without too much work. https://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver is in the top 5, again not Java but the API is very similar.


WebElement selectgender = driver.findElement(By.id("gender"));
selectgender.sendKeys("Male");

WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
   if("Germany".equals(option.getText()))
       option.click();   
}