Selenium WebDriver可以结合ExpectedCondition类来定义自己期望的条件
创建一个新的ExpectedCondition接口,必须实现apply方法
等待元素出现
1
public
void
testWithImplicitWait(){
2
System.setProperty("webdriver.chrome.driver", "chromedriver.exe"
);
3
WebDriver driver =
new
ChromeDriver();
4
driver.get("http://map.baidu.com"
);
5
6
//
点击展开当前城市
7
WebElement curCity = driver.findElement(By.id("curCity"
));
8
curCity.click();
9
10
//
设置等待时间10秒
11
WebDriverWait wait =
new
WebDriverWait(driver,10
);
12
//
创建一个新的ExpecctedCondition接口,就必须实现apply方法
13
WebElement message =
wait.until(
14
new
ExpectedCondition<WebElement>
(){
15
public
WebElement apply(WebDriver d){
16
return
d.findElement(By.id("selCityHotCityId"
));
17
}
18
}
19
);
20
21
driver.quit();
22
}
等待元素属性值改变
基于某些事件的操作后,元素的属性值可能会改变。例如,一个不可输入的文本框变为可输入状态。自定义的等待可以在元素的属性上实现。
在这个例子中,ExpectedCondition类将等待返回Boolean值
1
(
new
WebDriverWait(driver, 10).util(
new
ExpectedCondition<Boolean>
(){
2
public
Boolean apply(WebDriver d){
3
return
d.findElement(By.id("username"
)).
4
getAttribute("readonly").contains("true"
);
5
}
6
}));
等待元素变为可见
开发人员会隐藏或是在一系列操作后显示某元素。指定的元素一开始已经存在于DOM中,但是为隐藏状态,当用户经过指定的操作后变为可见。那么这样的自定义期望条件应该如下:
1
(
new
WebDriverWait(driver, 10).util(
new
ExpectedCondition<Boolean>
(){
2
public
Boolean apply(WebDriver d){
3
return
d.findElement(By.id("xxx"
)).isDisplayed();
4
}
5
}));
等待DOM事件
自定义的等待可以通过执行一段javascript代码并检查返回值来完成
1
(
new
WebDriverWait(driver,10)).until(
new
ExpectedCondition<Boolean>
(){
2
public
Boolean apply(WebDriver d){
3
JavascriptExecutor js =
(JavascriptExecutor) d;
4
return
(Boolean)js.executeScript("return jQuery.active == 0"
);
5
}
6
});

