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


当前回答

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

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

其他回答

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

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

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

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

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

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

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

在脚本中调用下面的函数,这将等待页面未使用javascript加载

public static boolean isloadComplete(WebDriver driver)
{
    return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
            || ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}

在我的例子中,我使用以下方法来了解页面加载状态。在我们的应用程序加载gif(s)是存在的,我听他们如下,以消除不必要的等待时间在脚本。

public static void processing(){ 
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='Msgpanel']/div/div/img")));
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@id='Msgpanel']/div/div/img")));
}

xpath在HTML DOM中定位gif的位置。 在此之后,您还可以实现您的动作方法单击。

public static void click(WebElement elementToBeClicked){
    WebDriverWait wait = new WebDriverWait(driver, 45);
    wait.until(ExpectedConditions.visibilityOf(element));
    wait.until(ExpectedConditions.elementToBeClickable(element)); 
    wait.ignoring(NoSuchElementException.class).ignoring(StaleElementReferenceException.class); elementToBeClicked.click(); 
 }

如果你想等待一个特定的元素加载,你可以在RenderedWebElement上使用isdisplay()方法:

// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
    // Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
    RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m"));

    // If results have been returned, the results are displayed in a drop down.
    if (resultsDiv.isDisplayed()) {
      break;
    }
}

(例子来自《5分钟入门指南》)