How to wait for page to load completely using JavaScript in Selenium

早过忘川 提交于 2019-12-10 11:59:46

问题


I'm trying get for page to load completely before doing an action. I don't want to start an action while loading circle on the browser tab is still turning. My wait for ajax function is not working for some cases, especially for new page loading. My function is JQuery based:

JavascriptExecutor jsDriver = (JavascriptExecutor) webDriver;
boolean stillRunningAjax = (Boolean) jsDriver
        .executeScript("return window.jQuery != undefined && jQuery.active != 0");
return !stillRunningAjax;

if that comes false, running it again.

But for page loading, after it returns true, browser is still loading (loading circle is turning) for a couple of seconds more (sometimes much more).

I've tried implicitlyWait but it stops the function at the same time with my function.

Some says there is not a complete solution for this in selenium. But there should be. Maybe a JavaScript included solution, anything.


回答1:


Using javascript to wait for page to load:

void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
    ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
        }
    };
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}

If you're waiting for an ajax to display an element on page, you can wait for the element itself.

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));


来源:https://stackoverflow.com/questions/30848249/how-to-wait-for-page-to-load-completely-using-javascript-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!