简体   繁体   English

如何在 Selenium 中使用 JavaScript 等待页面完全加载

[英]How to wait for page to load completely using JavaScript in Selenium

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.我的等待 ajax 功能在某些情况下不起作用,尤其是对于新页面加载。 My function is JQuery based:我的函数是基于 JQuery 的:

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).但是对于页面加载,在它返回 true 之后,浏览器仍在加载(加载循环正在转动)几秒钟(有时更多)。

I've tried implicitlyWait but it stops the function at the same time with my function.我已经尝试过 implicitlyWait 但它与我的函数同时停止了该函数。

Some says there is not a complete solution for this in selenium.有人说硒没有完整的解决方案。 But there should be.但应该有。 Maybe a JavaScript included solution, anything.也许一个包含 JavaScript 的解决方案,任何东西。

Using javascript to wait for page to load:使用 javascript 等待页面加载:

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.如果您正在等待 ajax 在页面上显示元素,则可以等待元素本身。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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