Reputation: 1128
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;
}
}
Upvotes: 4
Views: 50396
Reputation: 147
We can use java 8 stream API to filter and collect Web elements in an Array. Clicking will be easier using index.
// Collect 5 autocomplete entries lists
List<WebElement> list = driver.findElements(By.cssSelector("#ui-id-1
li:nth-child(n)")).stream()
.limit(5)
.collect(Collectors.toList());
// This will click the first element from an autocompleted list
list.get(0).click();
Upvotes: 0
Reputation: 2938
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();
}
}
Upvotes: 1
Reputation: 66
driverName.findElement(By.xpath("XPATH Location")).sendKeys("KeyNameYouWantToSearch" , Keys.TAB);
Upvotes: 0
Reputation: 1128
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.xpath("//div[@class='sbqs_c']"));
for(WebElement option : optionsToSelect){
System.out.println(option);
if(option.getText().equals(textToSelect)) {
System.out.println("Trying to select: "+textToSelect);
option.click();
break;
}
}
Upvotes: 1