如何让Selenium 2.0等待页面加载?


当前回答

我不认为含蓄的等待是你想要的。试试这个:

.timeouts driver.manage()()。TimeUnit.SECONDS pageLoadTimeout(10日);

更多信息请参见文档

其他回答

如果你设置了驱动程序的隐式等待,然后调用findElement方法在你期望加载页面上的元素上,WebDriver将轮询该元素,直到找到该元素或达到超时值。

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

来源:implicit-waits

public static int counter = 0;

public void stepGeneralWait() {

    boolean breakIt = true;

    while (true) {
        breakIt = true;
        try {

            do{
                // here put e.g. your spinner ID
                Controller.driver.findElement(By.xpath("//*[@id='static']/div[8]/img")).click();
                Thread.sleep(10000);

                counter++;

                if (counter > 3){
                    breakIt = false;

                }
            }
            while (breakIt);



        } catch (Exception e) {
            if (e.getMessage().contains("element is not attached")) {
                breakIt = false;
            }
        }
        if (breakIt) {
            break;
        }

    }

    try {
        Thread.sleep(12000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

这似乎是WebDriver的一个严重限制。显然,等待一个元素并不意味着页面正在加载,特别是DOM可以完全构建(onready状态),此时JS仍在执行,CSS和图像仍在加载。

我相信最简单的解决方案是在onload事件上设置一个JS变量,在所有东西初始化后,在Selenium中检查和等待这个JS变量。

如何让Selenium在单击后等待页面加载提供了以下有趣的方法:

存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。

示例代码:

WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
    try
    {
        link.isDisplayed();
        return false;
    }
    catch (StaleElementReferenceException unused)
    {
        return true;
    }
});
private static void checkPageIsReady(WebDriver driver) {
    JavascriptExecutor js = (JavascriptExecutor) driver;

    // Initially bellow given if condition will check ready state of page.
    if (js.executeScript("return document.readyState").toString().equals("complete")) {
        System.out.println("Page Is loaded.");
        return;
    }

    // This loop will rotate for 25 times to check If page Is ready after
    // every 1 second.
    // You can replace your value with 25 If you wants to Increase or
    // decrease wait time.
    for (int i = 0; i < 25; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        // To check page ready state.
        if (js.executeScript("return document.readyState").toString().equals("complete")) {
            break;
        }
    }
}