How I can check whether a page is loaded completely or not in web driver?

前端 未结 9 1843
走了就别回头了
走了就别回头了 2020-12-01 01:33

I am writing some Java Webdriver code to automate my application. How can I correctly check whether the page has been loaded or not? The application has some Ajax calls, too

9条回答
  •  鱼传尺愫
    2020-12-01 02:21

    Below is some code from my BasePageObject class for waits:

    public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
        WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
        wait.until(ExpectedConditions.titleContains(pageTitle));
    }
    
    public void waitForElementPresence(By locator, int seconds) {
        WebDriverWait wait = new WebDriverWait(driver, seconds);
        wait.until(ExpectedConditions.presenceOfElementLocated(locator));
    }
    
    public void jsWaitForPageToLoad(int timeOutInSeconds) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        String jsCommand = "return document.readyState";
    
        // Validate readyState before doing any waits
        if (js.executeScript(jsCommand).toString().equals("complete")) {
            return;
        }
    
        for (int i = 0; i < timeOutInSeconds; i++) {
            TimeManager.waitInSeconds(3);
            if (js.executeScript(jsCommand).toString().equals("complete")) {
                break;
            }
        }
    }
    
       /**
         * Looks for a visible OR invisible element via the provided locator for up
         * to maxWaitTime. Returns as soon as the element is found.
         *
         * @param byLocator
         * @param maxWaitTime - In seconds
         * @return
         *
         */
        public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
            if (driver == null) {
                nullDriverNullPointerExeption();
            }
            FluentWait wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
                    .pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);
    
            try {
                return wait.until((WebDriver webDriver) -> {
                    List elems = driver.findElements(byLocator);
                    if (elems.size() > 0) {
                        return elems.get(0);
                    } else {
                        return null;
                    }
                });
            } catch (Exception e) {
                return null;
            }
        }
    

    Supporting methods:

         /**
         * Gets locator.
         *
         * @param fieldName
         * @return
         */
        public By getBy(String fieldName) {
            try {
                return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
            } catch (NoSuchFieldException e) {
                return null;
            }
        }
    

提交回复
热议问题