Search code examples
javaseleniumselenium-webdriverxpathe-commerce

Search for mobiles and click a particular mobile and print a particular review of the product in the console


When we search for mobiles on Amazon and click a particular mobile and print a particular review of the product in the console using selenium with java with cucumber framework, Its is not printing anything.

     @Then("Click on the add to cart button")
     public void click_on_the_add_to_cart_button() {

    Set<String> ids = driver.getWindowHandles();
    Iterator<String> it = ids.iterator();
    String parentId = it.next();
    String childId = it.next();
    driver.switchTo().window(childId);
    l1=new LoginPojo();
    btnClick(l1.getAddToCart());
    JavascriptExecutor js =(JavascriptExecutor) driver;
    js.executeScript("window.scrollBy(0,10000)","");
    String data = driver.findElement(By.xpath(" //[@id=\"customer_review- R1R9S770F79ZNP\"]/div[4]/span/div/div[1]/span")).getText();
    System.out.println("Result: " + data);
}

Solution

  • See if this works. I am trying to grab the 4 element from this link

    List<WebElement> reviews = driver.findElements(By.xpath("//div[@data-hook='review']"));
            
    JavascriptExecutor js = (JavascriptExecutor)driver;
    WebElement reviewEle = reviews.get(4);
    js.executeScript("arguments[0].scrollIntoView(true);", reviewEle);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            
    System.out.println(reviewEle.findElement(By.xpath(".//div[contains(@id,'review-card')]/div[contains(@id,'customer_review')]//following-sibling::div[contains(@class,'small review-data')]//span[@data-hook='review-body']")).getText());