如何在 Selenium 中使用 JavaScript 等待页面完全加载 [英] How to wait for page to load completely using JavaScript in Selenium

查看:106
本文介绍了如何在 Selenium 中使用 JavaScript 等待页面完全加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在执行操作之前让页面完全加载.我不想在浏览器选项卡上的加载圆圈仍在转动时开始操作.我的等待 ajax 功能在某些情况下不起作用,尤其是对于新页面加载.我的函数是基于 JQuery 的:

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.

但是对于页面加载,在返回 true 后,浏览器仍在加载(加载圆圈正在转动)多几秒钟(有时更多).

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.

有人说在 selenium 中没有完整的解决方案.但应该有.也许一个包含 JavaScript 的解决方案,任何东西.

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:

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);
}

如果您正在等待 ajax 在页面上显示元素,您可以等待元素本身.

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")));

这篇关于如何在 Selenium 中使用 JavaScript 等待页面完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆