How to get all options in a DropDown list in Selenium WebDriver

 
 

In this tutorial, we will get to know how we can get the option values of a dropdown using Webdriver. This can be done by using getOptions().

getOptions( ) : List – It shows all options belonging to the Select tag. It takes no parameter and returns List.

oSelect.getOptions();

Below is an example on how to use getOptions. We want to print all the options of Drop Down Month.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class DropDown_Options {
      public static void main(String[] args) {
         System.setProperty(“webdriver.gecko.driver”,“C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe”);
            FirefoxDriver driver = new FirefoxDriver();
                  
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            driver.get("https://www.facebook.com/";);          
            
Select mselect = new Select(driver.findElement(By.id(“month”)));       
            
            // Print all the options for the selected drop down and select one option of your choice
            // Get the size of the Select element
            List mSize = mselect.getOptions();
            int OptionSize = mSize.size();                                   
           
            // Setting up the loop to print all the options
            for(int i =0; i < OptionSize ; i++)
          {
           
          // Storing the value of the option
           String Options = mselect.getOptions().get(i).getText();
           
          // Printing the stored value
           System.out.println(Options);
        }
   }
}

Output
Month
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s