http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
隐式等待(Implicit Wait )
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
隐式等待目的是让WebDriver在查找某个或某类元素时候容留一定的时间来进行检查。在这个时间内,如果找到就返回。否则就等到超过设置的时间并告知没有找到。这个时间默认设置为0。当我们设定了这个时间后,在我们下一次设定前,这个时间一直就是隐式等待的时间。代码示例如下:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
显示等待(Explicit Wait )
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code.The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait.There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.显示等待的好处是我们不但可以设置等待的时间,还可以甚至等待终止的条件,也就是我们期望的结果条件。当终止条件没有达到时候,等待就有点类似与Thread.sleep(),会抛出一个TimeoutException。写这类代码有一些巧方法,一种是结合使用WebDriverWait和ExpectedCondition。
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds.WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return isfor ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.
它会在10s内找到元素或者等10s然后抛出超时异常。默认WebDriverWait会每500毫秒调用一次ExpectedCondition直到成功返回。成功返回对于boolean型的ExpectedCondition为true,而对于其他类型的ExpectedCondition则为非null的返回值。上面这个例子在效果上等价于隐式等待的例子。
There are some common conditions that are frequently come across when automating web browsers. Listed below areImplementations of each. Java happens to have convienence methods so you don’t have to code an ExpectedConditionclass yourself or create your own utility package for them.
针对网页浏览器的自动化,已经提供了一些常用的ExpectedCondition。详细可以参考:http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
下面给一个例子展示自定义的个性化ExpectedCondition。
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.ignoring(WebDriverException.class);
wait.until(new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver webDriver)
{
if(webDriver.findElement("//button[text()='Upload']"))
return true;
return false;
}
});