简体   繁体   中英

Webdriver doesn't counts the elements on page properly (JAVA SELENIUM)

I'm trying to count the elements on the page. It worked for almsot a whole year perfectly fine but now my method is always giving a wrong value so my assertion fails. It gives random numbers that dont have any logical relationship.

public int getCountOfResults (Webdriver webdriver) {
    try {
         waitUntilFoundByLocatorAndIsDisplayed(webDriver,By.xpath("//div[@class='hello']/div/a"));
         List <WebElement> countProduct = webDriver.findElements(By.xpath("//div[@class='hello']/div/a"));
         return countProduct.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Seems you were close. However we don't have the visibility to the method waitUntilFoundByLocatorAndIsDisplayed() . As a solution you can induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use the following solution:

public int getCountOfResults (Webdriver webdriver) {
    try {
        waitUntilFoundByLocatorAndIsDisplayed(webDriver,By.xpath("//div[@class='hello']/div/a"));
        List <WebElement> countProduct = new WebDriverWait(webDriver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='hello']/div/a")));
        return countProduct.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM