How can I get all elements from a drop down list? I used the code below:
List<WebElement> elements = driver.findElements(By.id("s"));
But I am always getting the first element only.
Select select = new Select(driver. findElement(By.id("oldSelectMenu"))); // Get all the options of the dropdown List<WebElement> options = select. getOptions(); Using this method, we can retrieve all the options of a dropdown (be it single-select or multi-select ).
We can get a selected option in a dropdown in Selenium webdriver. The method getFirstSelectedOption() returns the selected option in the dropdown. Once the option is fetched we can apply getText() method to fetch the text.
To get an XPATH of an element right-click the Dropdown menu and select 'Inspect element with Firebug'. Then corresponding code would be highlighted in the firebug, right-click on it and select copy XPath. By this method we can copy the XPATH and paste it into the Selenium IDE tool's Target section.
There is a class designed for this in the bindigs.
You are looking for the Select
class:
https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/support/ui/Select.java
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With