Reputation: 15
With Selenium webdriver, I am trying search 'Selenium' in google search box, which provides auto suggestions of several texts. Then I am trying to click one particular text from auto suggestions list. It seems though, my Xpath is not working.
Below is the code I wrote:
package com.initial.selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GoogleSearch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Shahid\\eclipse-
workspace\\InitialSeleniumProject\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//*[@name='q']")).sendKeys("selenium");
List < WebElement >
mylist=driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']/span"));
System.out.println(mylist.size());
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i).getText());
if (mylist.get(i).getText().contains("Selenium Benefits")) {
mylist.get(i).click();
break;
}
}
}
Upvotes: 0
Views: 2099
Reputation: 11
Try this:
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//ul[@role='listbox']//li/descendant::span"), 0));
System.out.println("no. of suggestions:"+options.size());
for(int i=0;i<options.size();i++) {
System.out.println(options.get(i).getText());
}
Upvotes: 1
Reputation: 392
In this case, the error you're getting (a null result) is because the ul element you're targeting doesn't contain any elements.
So, in this case, you're going to change your target. Instead of doing:
ul[@role='listbox']
Do
li[@role='presentation']
And that will result in
//li[@role='presentation']/descendant::div[@class='sbl1']/span
Which returns the span you're trying to get.
Upvotes: 0