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


当前回答

在Webdriver/Selenium 2软件测试工具中有两种类型的等待。一种是隐式等待,另一种是显式等待。两者(隐式等待和显式等待)在WebDriver中都很有用。使用等待,我们告诉WebDriver在进入下一步之前等待一定的时间。可以使用隐式等待来等待页面加载。

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

其他回答

Imran对Java 7的回答是:

    WebDriverWait wait = new WebDriverWait(driver, 30);

    wait.until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver wdriver) {
            return ((JavascriptExecutor) driver).executeScript(
                "return document.readyState"
            ).equals("complete");
        }
    });

如何让Selenium在单击后等待页面加载提供了以下有趣的方法:

存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。

示例代码:

WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
    try
    {
        link.isDisplayed();
        return false;
    }
    catch (StaleElementReferenceException unused)
    {
        return true;
    }
});

对于使用java 8向前的程序员,可以使用下面的代码来使用显式等待等待页面加载。

JavascriptExecutor js = (JavascriptExecutor) driver;  
new WebDriverWait(driver, 10).until(webDriver ->
(js).executeScript("return document.readyState;").equals("complete"));

注意:在我上面的代码中使用Lambda表达式,它只在java 8的后续版本中可用。

对于使用低版本Java(即Java 8以下)的程序员,可以使用:

ExpectedCondition<Boolean> cond = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver input) {
        JavascriptExecutor js = (JavascriptExecutor) driver; 
        return js.executeScript("return document.readyState;").equals("complete");
            }
        };
         
    new WebDriverWait(driver, 100).until(cond);

The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.

http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html

隐式和显式的等待更好。

但是如果你在Java中处理一个异常,那么你可以使用这个来等待页面重新加载:

Thead.sleep(1000);