Many web applications now have auto suggest feature where in the suggestions appear as you type. The best known example is Google. There are two ways to select the auto-suggested item in the page

  • By mouse click
  • By key press (down/up arrows)

To automate the auto-suggest using mouse click requires you to identify the locator for the auto-suggest element and perform a click on it. Alternatively you can use key press actions to select the desired item and press enter.  Here is the webdriver code for selecting using key press

package com.sklabs.webdriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class AutoSuggestExample {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        WebElement search = driver.findElement(By.id("gbqfq"));
        search.sendKeys("selenium");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        Actions action = new Actions(driver);
        action.sendKeys(search, Keys.ARROW_DOWN).perform();
        action.sendKeys(search, Keys.ARROW_DOWN).perform();
        action.sendKeys(search, Keys.RETURN).perform();
        driver.close();
}

The caveat with this approach is that your test will fail if the auto-suggestion at the given row is not same always.
You can use this when you want to test that your application’s auto-suggest feature works with key press.