How to select a text from the autocomplete textbox using selenium

Ashok kumar Ganesan picture Ashok kumar Ganesan · Jun 16, 2015 · Viewed 39.6k times · Source

I need to enter some text in a autocomplete textbox. Then I will select a option from that autocomplete option and need to click it.

I have tried with the following code:

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    String textToSelect = "headlines today";

    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.google.co.in/");
    Thread.sleep(2000);
    WebElement autoOptions= driver.findElement(By.id("lst-ib"));
    autoOptions.sendKeys("he");

    List<WebElement> optionsToSelect = driver.findElements(By.tagName("li"));

    for(WebElement option : optionsToSelect){
        System.out.println(option);
        if(option.getText().equals(textToSelect)) {
            System.out.println("Trying to select: "+textToSelect);
            option.click();
            break;
        }
    }

Answer

eduliant picture eduliant · Jun 16, 2015

you can do like this i have used google home page auto suggest as an example

public class AutoSelection {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.google.com");

        driver.findElement(By.name("q")).sendKeys("mahatama gandhi");
        List<WebElement> autoSuggest = driver.findElements(By
            .xpath("//div[@class='sbqs_c']"));
        // verify the size of the list
        System.out
            .println("Size of the AutoSuggets is = " + autoSuggest.size());
        // print the auto suggest
        for (WebElement a : autoSuggest)
            System.out.println("Values are = " + a.getText());
        // suppose now you want to click on 3rd auto suggest then simply do like
        // this
        autoSuggest.get(2).click();
    }
}