i

Selenium Step By Step Guide

Handling Multiple Dropdown values and Links

As we have the first part of drop-down handling in previous topics. Now we focus on handling multiple drop-down options and discuss to handle drop-down when any Select tag does not surround the drop-down element.

Here we can observe that the drop-down element does not have any Select tag in it. So this situation needs to be handled differently. Instead of taking the main drop-down element, we take a common XPath for all the drop-down options. This means the XPath for “Banking & Insurance”, “SSC & Railway” and other option under “GOVERNMENT JOB" drop-down is the same.

So let us first get the common XPath for all the options inside the “GOVERNMENT JOB” drop-down.

List <WebElement> elements=driver.findElements(By.xpath("/html/body/header/div[4]/div/ul/li[1]/div/ul/li"));

We have kept this as list of elements as it has more than one element in this collection. Now let us check the number of elements/options present in this list.

int iSize=elements.size();

iSize variable will provide us the total number of elements present in this list and help us to select any option in the drop-down list now. Let us just create a string variable for the option to be selected.

String option="Upsc";

Now if we run a loop for selecting an option having text as “Upsc” then our objective of selecting an option will get completed.

for(int i=0;i<iSize;i++)

        {

               if(elements.get(i).getText().contains(option))

               {

                               System.out.println(elements.get(i).getText());

                               elements.get(i).click();

                  }   

}

Users can select any drop-down option based on the string provided. By using this way, we can select any option available in the drop-down box. Let us see the complete code for selecting a drop-down where the drop-down element is not of Select tag type.

package SeleniumTest.SeleniumTest;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class DropDownWithoutSelect

{

    public static void main( String[] args )

    {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\AC42610\\chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.get("https://selflearning.io/study-material/selenium");

        List <WebElement> elements=driver.findElements(By.xpath("/html/body/header/div[4]/div/ul/li[1]/div/ul/li"));

        String option="Upsc";

        int iSize=elements.size();

        System.out.println(iSize);

        for(int i=0;i<iSize;i++)

        {

            if(elements.get(i).getText().contains(option))

            {

                  System.out.println(elements.get(i).getText());

                  elements.get(i).clear();

            }

        }

        driver.quit();

    }

}