ScreenshotNeo

BlogHow-to

How to Handle Auto-Suggestions in Selenium with Java

Handle Selenium autocomplete by waiting for the right suggestion state, selecting it with the widget’s supported interaction, and verifying the result.

By the ScreenshotNeo team4 October 20269 min read

To handle auto-suggestions in Selenium with Java, first identify whether the control is a native HTML <select> or a custom JavaScript autocomplete. Type into the input, wait for the specific suggestion state you need, select it using the widget’s supported click or keyboard behavior, and verify the accepted value or state. Selenium’s Select class works only with native <select> elements; it does not control custom dropdowns made from elements such as div or li.

Autocomplete is asynchronous on many pages: navigation completing does not mean results are ready. Use an explicit wait tied to the actual widget state instead of immediately locating a result or adding an arbitrary sleep.

1. Identify the autocomplete type

Inspect the DOM and the behavior before choosing an API. A control that looks like a dropdown may still be a custom overlay.

What the page uses How to interact
Native <select> with <option> children Use Selenium’s Java Select class.
Text input with a custom suggestion panel Type into the input, wait for the desired result, then click it or use the widget’s keyboard controls.
Custom control that opens on focus or after a minimum number of characters Reproduce the required focus and typing behavior, then wait for the panel’s real ready state.

For a custom widget, determine which elements represent the input, visible result rows, loading state, and accepted value. Check whether results change with each keystroke and whether the widget supports arrow keys and Enter. Locators and key sequences depend on the page’s markup and behavior.

2. Set up Selenium for Java

Add Selenium Java to the project using the build tool and version appropriate for your application. Selenium’s official Java library installation guide documents the current setup options. The example below assumes a Java project with Selenium available as a dependency and a browser driver configured for your environment.

Import the relevant Selenium classes:

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

3. Handle a custom autocomplete by clicking a result

This adaptable example shows the sequence for a custom input and suggestion overlay. Replace the URL, selectors, expected label, and timeout with values for the page under test. It assumes the desired result is exposed as a visible element with the expected text.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));

WebElement input = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("city-input"))
);
input.clear();
input.sendKeys("San");

By desiredSuggestion = By.xpath(
    "//li[contains(@class, 'suggestion') and normalize-space(.)='San Francisco']"
);
WebElement suggestion = wait.until(
    ExpectedConditions.visibilityOfElementLocated(desiredSuggestion)
);
suggestion.click();

wait.until(ExpectedConditions.attributeToBe(input, "value", "San Francisco"));
if (!"San Francisco".equals(input.getAttribute("value"))) {
    throw new AssertionError("Autocomplete did not accept the expected city");
}

The locator is only an example. Some sites render suggestions as buttons, listbox options, or other elements. Scope the locator to the currently open widget and match the desired result, not simply the first row. The final assertion checks the input value; for another control, assert its selected state or the application-specific outcome that means the choice was accepted.

In a test method, ensure the driver lifecycle is handled by your test framework or a try/finally block so the browser is closed after success or failure. Do not close a shared driver inside a helper that the test still needs.

4. Select a suggestion with the keyboard

Some autocomplete widgets are designed for keyboard navigation. Send the keys the widget supports and verify the value after confirmation. For example, if typing leaves the desired item first in the active results and the widget documents Arrow Down followed by Enter, the interaction can look like this:

WebElement input = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("city-input"))
);
input.clear();
input.sendKeys("San");

wait.until(ExpectedConditions.visibilityOfElementLocated(
    By.cssSelector(".suggestion-list")
));
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ENTER);

wait.until(ExpectedConditions.attributeToBe(input, "value", "San Francisco"));

This key sequence is not universal. A widget may require multiple arrow presses, use a different active item rule, or accept the highlighted result with another key. Confirm the behavior from the page’s accessibility semantics and application code, or observe it manually, then encode that behavior in the test. If the list can reorder, assert which item is active before pressing Enter where possible.

5. Handle native select elements

If inspection confirms the control is a real <select>, use Selenium’s Select wrapper. Do not use it on a custom overlay.

import org.openqa.selenium.support.ui.Select;

WebElement countryElement = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("country"))
);
Select country = new Select(countryElement);
country.selectByVisibleText("Canada");

wait.until(ExpectedConditions.elementSelectionStateToBe(
    By.cssSelector("#country option:checked"), true
));

Depending on the page, verify the selected option’s value or visible text as the application contract requires. Selenium documents the native select limitations and supported selection methods in its select list elements guide.

6. Wait for the state that matters

An explicit wait polls for a condition and proceeds when it becomes true. Choose a condition that represents readiness for the next action:

  • Panel opened: wait for the suggestion container to be visible.
  • Desired result arrived: wait for the result matching the expected text to be visible.
  • Loading finished: wait for the spinner to disappear, if that is a reliable signal.
  • Selection accepted: wait for the input value, selected option, or relevant application state to change.

Example of waiting for a particular text result:

By result = By.cssSelector(".suggestion[role='option']");
wait.until(ExpectedConditions.textToBePresentInElementLocated(
    result, "San Francisco"
));
WebElement target = wait.until(
    ExpectedConditions.visibilityOfElementLocated(result)
);
target.click();

When an off-the-shelf condition does not describe the widget, use a custom wait predicate. For instance, this waits until at least one visible result has the exact desired text:

WebElement target = wait.until(driver ->
    driver.findElements(By.cssSelector(".suggestion"))
        .stream()
        .filter(WebElement::isDisplayed)
        .filter(element -> "San Francisco".equals(element.getText().trim()))
        .findFirst()
        .orElse(null)
);
target.click();

Set the timeout based on the application’s expected response and test environment, rather than treating the illustrative five seconds as a Selenium requirement. Selenium cautions that mixing implicit and explicit waits can produce unpredictable total wait times. Prefer explicit waits for dynamic autocomplete state and avoid setting a global implicit wait alongside them. See Selenium’s waiting strategies and expected conditions.

7. Make the test reliable

  • Clear or replace existing input text deliberately. If the widget reacts to each keystroke, clearing and typing a fresh query can trigger a different sequence from editing existing text.
  • Wait for the desired result, not merely any suggestion. The first visible item may not be the intended one.
  • Scope selectors to the visible, active suggestion panel. Pages may keep hidden templates or old result nodes in the DOM.
  • After choosing, assert the accepted state. Visibility alone proves only that a result appeared.
  • When results update on every character, wait for the final query’s result. A result from an earlier query may briefly remain visible.
  • Use the actual interaction path under test. Click if users click; use keyboard events if keyboard selection is the behavior being tested.
  • Keep synchronization condition-based. A fixed sleep can be too short on a slow run and waste time when results arrive quickly.

Selenium’s element interaction documentation describes text input and interactability behavior. For lower-level pointer and keyboard sequences, see the Actions API.

8. Common errors and fixes

Symptom Likely cause Fix
NoSuchElementException immediately after typing The result has not yet been inserted, or the locator does not match the page. Wait for the desired visible result and inspect the live DOM to correct the locator.
The test clicks the wrong suggestion The locator matches the first result or an old result instead of the requested label. Match the exact expected text and scope to the currently visible panel.
Wait times out even though suggestions appear The wait condition is aimed at the wrong node/state, or the selector matches a hidden template. Inspect which element becomes visible and wait for that state or expected text.
ElementClickInterceptedException An overlay, animation, or another element covers the result, or the dropdown is not in its ready state. Wait for the panel and target to be visible and interactable; inspect what is covering it. Do not hide the problem with a JavaScript click unless that is specifically the behavior being tested.
ElementNotInteractableException The located node is hidden, disabled, or not the real interactive result. Locate the visible interactive element, wait for it to be enabled, and verify the panel is open.
StaleElementReferenceException after typing Typing caused the framework to replace the input or suggestion nodes. Re-find the element after the update and wait for the replacement node’s state; avoid retaining result references across rerenders.
Select throws an error or cannot choose an item The control is a custom dropdown, not a native <select>. Inspect the HTML and use ordinary element or keyboard interaction for the custom widget.
Keyboard selection chooses a different row Focus, active-row behavior, or result ordering differs from the assumption. Confirm focus is in the input, wait for results, inspect the active option, and send the necessary supported key sequence.

9. Performance, reliability, and cost considerations

Explicit waits make the test continue as soon as the expected condition is true, while bounding how long it waits when that condition never occurs. Arbitrary long sleeps slow every successful run and still do not guarantee readiness if the page takes longer. A narrowly scoped locator and a condition for the intended result also avoid selecting an unrelated element.

Autocomplete tests can depend on network-backed data, rate limits, geolocation, or changing result sets. Where the application provides a stable test dataset or a controlled test environment, use it. If results are intentionally variable, assert the relevant contract rather than a result whose ordering or availability changes outside the test’s control. Selenium does not prescribe a timeout that fits every site; choose one appropriate to the app and environment, and include useful query and locator context in failure output.

Selenium itself is browser automation software rather than a per-screenshot service, so the relevant costs are your browser infrastructure, execution time, and any application-side service usage. Keep screenshot or diagnostic capture on failure if your test framework supports it, so successful runs do not accumulate unnecessary artifacts.

10. Or skip the browser setup

If you need a page image for documentation, monitoring, or visual review rather than to test autocomplete interaction, ScreenshotNeo can return a screenshot or PDF from one API request. The API supports PNG, JPEG, WebP, and PDF; see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Replace the example target with the page you need and keep the access key out of source control. Cookie banners, newsletter popups, and chat widgets are removed before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers report the page verdict and billing status. ScreenshotNeo also provides an MCP server so AI agents can take screenshots. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.

Sign up free for 1,000 screenshots a month, with no card required.

11. FAQ

Can Selenium choose an autocomplete result by visible text?

Yes, if the custom widget exposes a visible result element you can locate reliably. Match the expected label, wait for it to be visible, select it, and verify the accepted state.

Should I use JavaScript to click a suggestion?

Usually, use the same user-facing click or keyboard action the widget supports. A JavaScript click can bypass interactability behavior and may not test the real interaction.

Why does the list disappear when I try to inspect or click it?

Some widgets close on blur or rerender after input changes. Keep focus in the input until results are ready, and inspect the widget’s focus and event behavior to choose a stable interaction sequence.

Does a screenshot prove an autocomplete test passed?

No. A screenshot can help diagnose what was rendered, but the test should assert the selected value or application state that represents acceptance.