Handling Dynamic Dropdown in Selenium

Profile picture for user arilio666

In this article, we will handle dynamic dropdowns, or we can call them dropdowns without a select tag. We can handle select tag dropdowns easily using the select class available in selenium.

  • This site right here has a different thing. It has no select tag. Then how do we handle them?
  • We can handle them using three methods.

1.) Using Direct Text Locator

  • We can use the XPath text locator and isolate the country we want to select.
//span[contains(text(),'Maldives')]
  • Using this xpath for this site, we can isolate the country Maldives and select it.
WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://autopract.com/selenium/dropdown4/");
        driver.manage().window().maximize();
        driver.findElement(By.tagName("button")).click();
        driver.findElement(By.xpath("//span[contains(text(),'Maldives')]")).click();
  • Likewise, we can change the country in the text field with the country we want to select and the selenium we choose them.

2.) Using For Loop.

  • Using for loop, we can get the list of elements from the countries available and iterate it.
int countryList = driver.findElements(By.xpath("//div[@role='combobox']")).size();
  • Get the size of the common webelement from countries isolated.
    for (int i = 0; i < countryList; i++) {
            String countryText = driver.findElements(By.xpath("//div[@role='combobox']")).get(i).getText();
            System.out.println(countryText);
            if (countryText.contains("Maldives")) {
                driver.findElements(By.xpath("//div[@role='combobox']")).get(i).click();
            }
        }
  • By passing the countryList within the for-loop, we can get the index 'i' and get the text out of them.
  • Here we can see the countries it got from the for loop in the console.
  • Simply after that, with the help of the if statement, we can use contains and click the element.

3.) Advanced For Loop.

This is the easiest method and far more straightforward than for loop.

        List<WebElement> countryList = driver.findElements(By.xpath("//div[@role='combobox']"));

Here is the list of webelements we are going to iterate using foreach.

        for (WebElement ele : countryList) {
            if (ele.getText().contains("Angola")) {
                ele.click();
            }
        }

For each, immediately create object ele, and using ele, we can get the text same as for loop and use contains inside if statement and fetch the element.