Software Development

Select Text from Autocomplete Fields with Selenium WebDriver

Autocomplete inputs are common in modern web apps for search, tagging, and form completion. Unlike simple text fields, these inputs render a suggestion list asynchronously and require additional interactions to choose a value. This article explains how to reliably select options from an autocomplete dropdown using Selenium.

1. Prerequisites and Project Setup

First, we need a Java project with Selenium dependencies and a test framework. This section shows how to configure a Maven project with WebDriverManager, so browser drivers are resolved automatically.

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.38.0</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>6.3.3</version>
        </dependency>

This configuration adds Selenium for browser automation and WebDriverManager to automatically download and configure the correct browser driver.

2. Sample HTML Page with Autocomplete Behavior

To demonstrate predictable behavior, we’ll use a small HTML page that shows suggestions dynamically as the user types. Real production apps behave similarly, but often with network calls instead of in-memory lists.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Autocomplete Demo</title>
        <style>
            .suggestions {
                border: 1px solid #ccc;
                max-width: 300px;
                display: none;
                position: absolute;
                background: white;
            }
            .suggestion-item {
                padding: 8px;
                cursor: pointer;
            }
            .suggestion-item:hover {
                background: #f0f0f0;
            }
        </style>
    </head>
    <body>

        <h3>Search Country</h3>
        <input id="searchBox" type="text" placeholder="Type a country..." autocomplete="off"/>

        <div id="suggestions" class="suggestions"></div>

        <script>
            const data = ["Nigeria", "Niger", "Netherlands", "Norway", "Namibia"];
            const input = document.getElementById("searchBox");
            const suggestionsBox = document.getElementById("suggestions");

            input.addEventListener("input", function () {
                const value = this.value.toLowerCase();
                suggestionsBox.innerHTML = "";
                if (!value) {
                    suggestionsBox.style.display = "none";
                    return;
                }

                const matches = data.filter(d => d.toLowerCase().startsWith(value));
                matches.forEach(m => {
                    const div = document.createElement("div");
                    div.className = "suggestion-item";
                    div.innerText = m;
                    div.onclick = () => {
                        input.value = m;
                        suggestionsBox.style.display = "none";
                    };
                    suggestionsBox.appendChild(div);
                });

                suggestionsBox.style.display = matches.length ? "block" : "none";
            });
        </script>

    </body>
</html>

Each keystroke triggers filtering and rendering of suggestions. This is important because it mimics real-world components that depend on incremental input events rather than final text values.

3. Base WebDriver Configuration

To avoid repeating browser setup code in every test, we define a reusable base class that manages driver lifecycle.

public abstract class BaseTest {

    protected WebDriver driver;

    @BeforeEach
    void setUp() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        driver.manage().window().maximize();
    }

    @AfterEach
    void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

This class initializes Chrome before each test and closes it afterward. Implicit wait is kept short and used only for basic element discovery.

4. Waiting for Autocomplete Suggestions Properly

Autocomplete suggestions load after a short delay, so implicit waits alone are not reliable. We should use explicit waits to make sure the dropdown is visible and ready to select, and type the text one character at a time to act like a real user and trigger the page’s JavaScript correctly.

public class WaitUtils {

    public static void typeSlowly(WebElement element, String text, long delayMillis) {
        for (char c : text.toCharArray()) {
            element.sendKeys(String.valueOf(c));
            try {
                Thread.sleep(delayMillis);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void waitForVisible(WebDriver driver, By locator) {
        new WebDriverWait(driver, Duration.ofSeconds(10))
                .until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
    }
}

typeSlowly sends each character separately and pauses briefly between keystrokes, which helps trigger suggestion logic tied to key events or debounced input handlers. waitForVisible ensures the test does not interact with suggestion elements before they are actually rendered.

5. Test Implementation

This approach types the query gradually, waits for suggestions to appear, and clicks the intended option from the dropdown.

public class AutocompleteTest extends BaseTest {

    @Test
    void selectSuggestionWithMouse() {
        driver.get("http://localhost:8080/index.html");

        WebElement searchBox = driver.findElement(By.id("searchBox"));

        WaitUtils.typeSlowly(searchBox, "Ni", 200);

        By suggestionsBox = By.id("suggestions");
        WaitUtils.waitForVisible(driver, suggestionsBox);

        WebElement nigeriaOption
                = driver.findElement(By.xpath("//div[@class='suggestion-item' and text()='Nigeria']"));
        nigeriaOption.click();

        assertEquals("Nigeria", searchBox.getAttribute("value"));
    }
}

The test begins by navigating the browser to the page that contains the autocomplete input field. Next, the test locates the search input field using its id attribute and stores it as a WebElement. Instead of entering the full word at once, the test types the characters "N" and "i" one after the other with a short delay between them.

After typing, the test waits explicitly until the suggestion dropdown becomes visible. This is done using an explicit wait rather than relying on timing assumptions. Once the dropdown is visible, the test locates a specific suggestion item using an XPath expression that matches both the CSS class and the visible text. This ensures that the correct option is selected, even if multiple suggestions are displayed simultaneously.

The test then clicks the selected suggestion, simulating the user’s choice of an option from the dropdown. Finally, the test verifies that the input field now contains the expected value. By checking the value attribute of the input element, the assertion confirms that the autocomplete selection was successful and that the UI behaved as expected after the click action.

5. Conclusion

In this article, we demonstrated how to interact with autocomplete inputs in Selenium by typing character by character, waiting for dynamic suggestions to appear, and selecting the desired option reliably. By combining explicit waits with human-like input behavior, we can reduce flaky tests and ensure our end-to-end tests reflect real user interactions more accurately.

6. Download the Source Code

This article explained how to select text from an autocomplete input using Selenium.

Download
You can download the full source code of this example here: selenium select text autocomplete

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button