Abdul Nassar M
Abdul Nassar M

Reputation: 55

How loop drop down value using Selenium JAVA

I have a dropdown with some countries as follows,

enter image description here

I want to send the values US,CA,AF,AL,DZ,AS,AD to an array, loop it and print by using Selenium and Java.

I tried the following

WebElement elementdrop = d.findElement(By.xpath("path"));
List<WebElement> dropdownvalues = d.findElements(By.xpath("path"));
for(WebElement value:dropdownvalues)
{ 
  String pcvalues=value.getText();
  System.out.println("value names" + pcvalues);
 }

This will print United States Canada Afghanistan Albania etc. But I want like US CA AF AL DZ AS AD

Upvotes: 1

Views: 4806

Answers (1)

Amit
Amit

Reputation: 136

 WebElement dropdown = driver.findElement(By.name("Country"));

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

 Iterator<WebElement> it=options.iterator();

   while(it.hasNext())
    {
      System.out.println(it.next().getAttribute("Value"));
    }

Give this a try and let me know if it works.

Upvotes: 3

Related Questions