0
List<WebElement> statusvalues = driver.findElements(By.id("ddlStatus"));
for (WebElement option : statusvalues)
{
  System.out.println(option.getText());         
}

This is the script I have used to write.

System not providing the error but I didn't get the result. There are five drop down values I need to write in the output. The HTML code is given below.

<select id="ddlStatus" name="Status" class="full-width" data-role="dropdownlist" style="display: none;">
    <option value="" selected="selected"> -- Select -- </option>
    <option value="11">Arts</option>
    <option value="13">Science</option>
    <option value="14">Engineering</option>
    <option value="64">Law</option>
    <option value="85">Teaching</option>
    <option value="87">Journalist</option>
</select>

Just exploring the selenium webdriver and how to write the drop down values in the output.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
Mukunth Rajendran
  • 143
  • 1
  • 2
  • 10
  • 1
    Possible duplicate of [How to get selected option using Selenium WebDriver with Java](http://stackoverflow.com/questions/11934966/how-to-get-selected-option-using-selenium-webdriver-with-java) – JeffC Jul 11 '16 at 13:46

3 Answers3

1

List<WebElement> statusvalues = driver.findElements(By.id("ddlStatus"));

it's an element and not collection of elements so you need to do:

WebElement selectElement = driver.findElement(By.id("ddlStatus"));

In that element you have options so you can make collection:

List<WebElement> options = selectElement.findElements(By.tagName("option"));

and now you can loop...

Try:

List<WebElement> statusvalues = driver.findElement(By.id("ddlStatus")).findElements(By.tagName("option"));
for (WebElement option : statusvalues)
{
   System.out.println(option.getText());         
}
Leon Barkan
  • 2,676
  • 2
  • 19
  • 43
0

For the best way you should try using Select for drop down as below :-

Select sel = new Select(driver.findElement(By.id("ddlStatus")));
List<WebElement> options = sel.getOptions();
for (WebElement option : options)
{
  System.out.println(option.getText());         
}

Note:- driver.findElements(By.id("ddlStatus")); only provides you the list of all Elements which has id ddlStatus so in this case you could get only the drop down element here not it's option.

Hope it will help you..:)

Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73
0

Also you can try this

   List <WebElement> options = driver.findElements(By.xpath("//*[@id='ddlStatus']/option"));
   for(WebElement option : options)
   {
       System.out.println(option.getText());         
    }

You can also handle the dropdowns in 3 other ways as follows,

new Select(driver.findElement(By.id("ddlStatus"))).selectByVisibleText("Particular Text");

new Select(driver.findElement(By.id("ddlStatus"))).selectByIndex(Particular index);

new Select(driver.findElement(By.id("ddlStatus"))).selectByValue("Particular value");