How to display all items in the list in the drop down in Selenium?

SeleniumAutomation TestingTesting Tools

We can display all items in the list in the dropdown with Selenium webdriver using the Select class. A dropdown is represented by select tag and itsoptions are represented by option tag.

To obtain all the list of items we have to use the method getOptions. Its return type is list. Then we have to iterate through this list and obtain it with the help of the getText method.

Let us see the html code of a dropdown along with its options – Please select an option, Option 1 and Option 2.

Syntax

WebElement d = driver.findElement(By.tagName("select"));
Select l = new Select(d);
List<WebElement> m = l.getOptions();

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.support.ui.Select
public class DrpdwnLst{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://the-internet.herokuapp.com/dropdown");
      // identify dropdown
      WebElement d = driver.findElement(By.tagName("select"));
      //Select class to get options in dropdown
      Select l = new Select(d);
      List<WebElement> m = l.getOptions();
      System.out.println("Drodown list items are: ");
      //iterate through options till list size
      for (int j = 0; j < m.size(); j++) {
         String s = m.get(j).getText();
         System.out.println(s);
      }
      driver.quit();}
   }
}

Output

raja
Published on 06-Apr-2021 08:28:18
Advertisements