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


当前回答

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

这段代码将等待页面上的所有元素都加载到DOM中。

WebDriver driver = new WebDriver();
WebDriverWait wait = new WebDriverWait(driver, timeout);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*")));

一般来说,使用Selenium 2.0时,web驱动程序应该只在确定页面已加载后才将控制权返回给调用代码。如果没有,您可以调用waitforeleement,它循环调用findelement,直到找到它或超时(可以设置超时)。

您可以使用下面的现有方法来设置pageLoadTimeout。在下面的例子中,如果页面加载时间超过20秒,那么它将抛出一个页面重新加载异常:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);

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

    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;