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


当前回答

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

其他回答

最简单的方法就是等待一些元素出现在加载页面上。

如果你想在页面加载后点击一些按钮,你可以使用等待,然后点击:

await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;

伙计,所有这些答案都需要太多代码。这应该是一个简单的事情,因为它很常见。

为什么不注入一些简单的Javascript与web驱动程序和检查。 这就是我在webscraper课上使用的方法。Javascript是相当基本的,即使你不知道它。

def js_get_page_state(self):
"""
Javascript for getting document.readyState
:return: Pages state. See doc link below.
"""
ready_state = self.driver.execute_script('return document.readyState')
if ready_state == 'loading':
    self.logger.info("Loading Page...")
elif ready_state == 'interactive':
    self.logger.info("Page is interactive")
elif ready_state == 'complete':
    self.logger.info("The page is fully loaded!")
return ready_state

更多信息见“文档”。MDN Web Docs的readyState: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

使用隐式等待等待页面上的每个元素直到给定的时间。

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

这将等待页面上的每个元素30秒。

另一种等待是显式等待或有条件等待,在这个等待直到给定条件。

WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

在id中,给出静态元素id,一旦页面加载,它就会不小心显示在页面上。

你也可以使用类:ExpectedConditions来显式地等待一个元素出现在网页上,然后你才能采取任何行动

你可以使用ExpectedConditions类来确定一个元素是否可见:

WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName")));

查看ExpectedConditions类Javadoc,了解您可以检查的所有条件的列表。

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

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