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
});
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

