Handling Auto-Suggestion Dropdown Lists in Selenium 4

What is an Auto-Suggestion Dropdown List?

Auto-suggestion dropdown lists allow users to type and select from a list of options that dynamically filter based on input. This behavior can be automated using Selenium for testing purposes.

Steps to Automate:

  1. Locate the input field.
  2. Send input to trigger the suggestions.
  3. Capture the list of suggestions.
  4. Select the desired suggestion (e.g., 4th item).

Example: Auto-Suggestion for Laptops

Selenium Script to Automate Selection


                import org.openqa.selenium.By;
                import org.openqa.selenium.WebDriver;
                import org.openqa.selenium.WebElement;
                import org.openqa.selenium.chrome.ChromeDriver;
                import java.util.List;

                public class AutoSuggestionDropdown {
                    public static void main(String[] args) throws InterruptedException {
                        System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
                        WebDriver driver = new ChromeDriver();
                        driver.get("https://shariqsp.com/autosuggestion.html");

                        // Locate input field
                        WebElement inputField = driver.findElement(By.id("laptopInput"));
                        inputField.sendKeys("laptop");

                        // Wait for suggestions to appear
                        Thread.sleep(2000);

                        // Capture suggestions
                        List suggestions = driver.findElements(By.cssSelector("#laptopDropdown li"));

                        // Select the 4th suggestion
                        if (suggestions.size() >= 4) {
                            suggestions.get(3).click();  // Index 3 for the 4th item
                        } else {
                            System.out.println("Not enough suggestions.");
                        }

                        // Close browser
                        Thread.sleep(2000);
                        driver.quit();
                    }
                }