2

I am trying to get the text for Rating of any product on Amazon but I am unable to write the correct code. I don't understand what I am doing wrong here. Here its not even able to locate the element. Also I don't think xpath is wrong because I checked with Firepath.

Below is the code:

public static void main(String args[])
{
    System.setProperty("webdriver.gecko.driver", "D:\\Eclipse and workspace\\eclipse\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();

    driver.get("https://www.amazon.in/");

    WebElement elem = driver.findElement(By.id("twotabsearchtextbox"));

    elem.sendKeys("Camera DSLR");

    driver.findElement(By.className("nav-input")).click();


    WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='result_0']/div/div/div/div[2]/div[3]/div[2]/div[1]/span/span/a/i[1]/span")));

    WebElement elem2 = driver.findElement(By.xpath(".//*[@id='result_0']/div/div/div/div[2]/div[3]/div[2]/div[1]/span/span/a/i[1]/span"));
    elem2.getText();

}

Please help me out.

Ritesh Gupta
  • 81
  • 2
  • 11

2 Answers2

3

The span element you want to get contains text like "4.4 out of 5 stars", but actually you see just an icon with the stars, so it's bad idea to use visibilityOfElementLocated condition as it won't be visible anyway.

Try to use presenceOfElementLocated instead:

WebElement elem2 = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@class='a-popover-trigger a-declarative']//span[@class='a-icon-alt']")));
elem2.getAttribute("textContent");

Note that to get text content of invisible span you should use getAttribute("textContent") instead of getText()

Andersson
  • 51,635
  • 17
  • 77
  • 129
0
  1. Use dynamic xpath instead of absolute xpath:

By.xpath("//*[contains(@class,'a-icon-star')]//*[contains(@class,'a-icon-alt')]")

And as rightly pointed out by @Andersson,

  1. Use presenceOfElementLocated instead of visibilityOfElementLocated as tooltips are designed to be invisible.

  2. Use textContent attribute for invisible elements such as tooltips instead of getText().

Zeeshan S.
  • 2,041
  • 2
  • 21
  • 40