Search code examples
javaseleniumxpathautomationnosuchelementexception

Selenium in Java: Not able to locate element on Amazon


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.


Solution

  • 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()