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


当前回答

你可以使用下面的代码片段来加载页面:

    IWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver,TimeSpan.FromSeconds(30.00));
    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

或者你可以使用waiter的任何元素被加载,并成为可见/可点击的页面上,最有可能的是,这将是在加载结束时加载,如:

    Wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(xpathOfElement));
    var element = GlobalDriver.FindElement(By.XPath(xpathOfElement));
    var isSucceededed = element != null;

其他回答

在我的例子中,我使用以下方法来了解页面加载状态。在我们的应用程序加载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(); 
 }

使用类WebDriverWait

也可以看这里

您可以期望显示一些元素。类似于c#:

WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0));

_wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement")));

对于隐式等待,你可以使用如下代码:

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

为了使网页等待一个特定的对象是可见的或某些条件是真实的。您可以使用网页驱动程序等羽。

//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);  
wait.until(ExpectedConditions.elementToBeClickable("CONDITITON"));

在Java中,另一种选择是让线程在特定的时间内休眠。

Thread.sleep(numberOfSeconds*1000); 
//This line will cause thread to sleep for seconds as variable

我创建了一个方法来简化线程。睡眠的方法

public static void wait_time(int seconds){
    try {
        Thread.sleep(seconds*1000);
        }catch (InterruptedException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

使用wait_time(10)方法;线程将休眠10秒。

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

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

await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).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分钟入门指南》)