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


当前回答

如果你想等待一个特定的元素加载,你可以在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分钟入门指南》)

其他回答

在脚本中调用下面的函数,这将等待页面未使用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(); 
 }

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

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,一旦页面加载,它就会不小心显示在页面上。

您还可以使用以下代码检查页面加载

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

 wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

WebDriver driver = new ff / chrome / anyDriverYouWish(); .timeouts driver.manage()()。TimeUnit.SECONDS implicitlyWait(10日); 最多等待10秒。 WebDriverWait wait = new WebDriverWait(driver, 10); wait.until (ExpectedConditions。visibilityOf (WebElement元素)); FluentWait <司机> FluentWait; fluentWait = new fluentWait <>(driver)。TimeUnit.SECONDS withTimeout(30日) TimeUnit.MILLISECONDS .pollingEvery (200) . ignore (NoSuchElementException.class);

最后一个选项的优点是可以包含预期的异常,以便继续执行。