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

user1754106 picture user1754106 · Oct 17, 2012 · Viewed 307.7k times · Source

How can I select an item from a drop down list like gender (eg male, female) using Selenium WebDriver with Java?

I have tried this

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

My above code didn't work.

Answer

some_other_guy picture some_other_guy · Oct 18, 2012

Use -

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

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