Selenium WebDriver可以結(jié)合ExpectedCondition類(lèi)來(lái)定義自己期望的條件
創(chuàng)建一個(gè)新的ExpectedCondition接口,必須實(shí)現(xiàn)apply方法
?
等待元素出現(xiàn)

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 // 點(diǎn)擊展開(kāi)當(dāng)前城市 7 WebElement curCity = driver.findElement(By.id("curCity" )); 8 curCity.click(); 9 10 // 設(shè)置等待時(shí)間10秒 11 WebDriverWait wait = new WebDriverWait(driver,10 ); 12 // 創(chuàng)建一個(gè)新的ExpecctedCondition接口,就必須實(shí)現(xiàn)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 }
?
等待元素屬性值改變
基于某些事件的操作后,元素的屬性值可能會(huì)改變。例如,一個(gè)不可輸入的文本框變?yōu)榭奢斎霠顟B(tài)。自定義的等待可以在元素的屬性上實(shí)現(xiàn)。
在這個(gè)例子中,ExpectedCondition類(lèi)將等待返回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 }));
?
等待元素變?yōu)榭梢?jiàn)
開(kāi)發(fā)人員會(huì)隱藏或是在一系列操作后顯示某元素。指定的元素一開(kāi)始已經(jīng)存在于DOM中,但是為隱藏狀態(tài),當(dāng)用戶(hù)經(jīng)過(guò)指定的操作后變?yōu)榭梢?jiàn)。那么這樣的自定義期望條件應(yīng)該如下:
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事件
自定義的等待可以通過(guò)執(zhí)行一段javascript代碼并檢查返回值來(lái)完成
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 });
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
