How can I get all elements from drop down list in Selenium WebDriver?
There is a class designed for this in the bindigs.
You are looking for the Select
class:
You would need to 'find' the actual select
element, not the individual options. Find that select
element, and let Selenium & the Select
class do the rest of the work for you.
You'd be looking for something like (s
being the actual select
element):
WebElement selectElement = driver.findElement(By.id("s");Select select = new Select(selectElement);
The Select
class has a handy getOptions()
method. This will do exactly what you think it does.
List<WebElement> allOptions = select.getOptions();
Now you can do what you want with allOptions
.
This will help to list all the elements from the dropdown:
Select dropdown = new Select(driver.findElement(By.id("id"))); //Get all options List<WebElement> dd = dropdown.getOptions(); //Get the length System.out.println(dd.size()); // Loop to print one by one for (int j = 0; j < dd.size(); j++) { System.out.println(dd.get(j).getText()); }
Namita,
with below code you will get list of options available in select box and you click on one.
List options = select.findElements(By.tagName("option"));
for(WebElement option : options){ if(option.getText().equals("male")) { option.click(); break; } }