Selenium Webdriver——设置等待时间

1.隐式等待

implicitlyWait():

当使用了隐士等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常

当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0

一旦设置了隐式等待,则它存在整个 WebDriver 对象实例的声明周期中,隐式的等到会让一个正常响应的应用的测试变慢,

它将会在寻找每个元素的时候都进行等待,这样会增加整个测试执行的时间。

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

2.显示等待

WebDriverWait():webdriver的针对某个元素的明确等待(explicitly wait)

详细格式如下:

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)

driver - WebDriver 的驱动程序(Ie, Firefox, Chrome 或远程)

timeout - 最长超时时间,默认以秒为单位

poll_frequency - 休眠时间的间隔(步长)时间,默认为0.5 秒

ignored_exceptions - 超时后的异常信息,默认情况下抛NoSuchElementException 异常。

 1     /**
 2      * 在给定的时间内去查找元素,如果没找到则超时,抛出异常
 3      * */
 4     public static void waitForElementToLoad(WebDriver driver, int timeOut, final By By) {
 5         try {
 6             (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {
 7 
 8                 public Boolean apply(WebDriver driver) {
 9                     WebElement element = driver.findElement(By);
10                     return element.isDisplayed();
11                 }
12             });
13         } catch (TimeoutException e) {
14             Assert.fail("超时!! " + timeOut + " 秒之后还没找到元素 [" + By + "]");
15         }
16     }

 

posted @ 2016-08-05 10:47  hjhsysu  阅读(5000)  评论(0编辑  收藏  举报