04
Sep

How to select an option from “AutoComplete” text field

Following code snippet demonstrates how to select an option from “AutoComplete” text field

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class SelectAnOptionFromAutoComplete {

@Test
public void selectAnAutoCompleteOption() {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“http://www.google.com”);

driver.findElement(By.name(“q”)).sendKeys(“Defectr”);
List autoSuggest = driver.findElements(By.xpath(“//div[@class=’sbqs_c’]”));
// print the size of the list
System.out.println(“Size of the AutoSuggets is = ” + autoSuggest.size());
int i=0;
// print the auto suggest
for (WebElement a : autoSuggest)
{
i=i+1;
System.out.println(“AutoComplete options “+i+”is = ” + a.getText());
}

//Select 2nd option
autoSuggest.get(2).click();

driver.quit();
}
}