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

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


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();   }