且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待Ajax请求完成-Selenium WebDriver

更新时间:2023-11-20 23:23:34

这是我用来等待Ajax完成的代码:

Here's the code I use to wait for Ajax to finish:

public static void waitForAjaxToFinish() {

    WebDriverWait wait = new WebDriverWait(driver, 5000);
    wait.until(new ExpectedCondition<Boolean>() {

        public Boolean apply(WebDriver wdriver) {
            return ((JavascriptExecutor) driver).executeScript("return jQuery.active == 0").equals(true);
        }

    });
}

以及我用来等待JQuery处于活动状态的代码:

and the code I use to wait until JQuery is active:

public static void waitForJQueryToBeActive() {
    Boolean isJqueryUsed = (Boolean) ((JavascriptExecutor) driver)
            .executeScript("return (typeof(jQuery) != 'undefined')");
    if (isJqueryUsed) {
        while (true) {
            // JavaScript test to verify jQuery is active or not
            Boolean ajaxIsComplete = (Boolean) (((JavascriptExecutor) driver)
                    .executeScript("return jQuery.active == 0"));
            if (ajaxIsComplete)
                break;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }
    }
}

希望这会有所帮助.