Selenium學習9--顯示等待,判斷頁面元素是否存在
html程式碼如下:
<html lang="en"> <head> <title>your favorite fruits</title> </head> <body> <p>select ur perfer fruit</p> <br> <select name='fruit'> <option id='peach' value='taozi'>peach</option> <option id='watermelon' value='xigua'>watermelon</option> </select> <br> <input type='checkbox'>Do you like fruits?</input> <br><br> <input type=text" id="text" value="Watermelons are so sweet this year!">This is Input box</input> </body> </html>
@Test public void testExplicitWait(){ driver.get("E:\\Java\\selenium_data\\html\\obviouswait.html"); //宣告一個WebDriverWait物件,設定復發條件的最長時間待定10s WebDriverWait wait = new WebDriverWait(driver,10); //呼叫ExpectedConditions的titleContains方法判斷頁面title屬性是否包含"fruits"欄位 wait.until(ExpectedConditions.titleContains("fruits"));
WebElement select = driver.findElement(By.xpath("//option[@id='peach']")); //elementToBeSelected(Element element)判斷"peach"是否被選中 wait.until(ExpectedConditions.elementToBeSelected(select));
//elementToBeClickable(String )判斷複選框物件是否可以被點選 wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//p")));
//presenceOfElementLocated 判斷元素是否存在 wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//x")));
//textToBePresentInElement判斷字樣是否在元素中顯示 WebElement p = driver.findElement(By.xpath("//p")); wait.until(ExpectedConditions.textToBePresentInElement(p, "select ur perfer fruit")); }
自定義顯示等待 @Test public void testCustomExplicitWait(){ driver.get("E:\\Java\\selenium_data\\html\\obviouswait.html"); try{ //顯示等待判斷是否可以從頁面獲取文字輸入框物件, 如果可以獲取, 則執行後續測試邏輯 WebElement textInputBox = (new WebDriverWait(driver,10).until(new ExpectedCondition<WebElement>() {
@Override public WebElement apply(WebDriver driver) { return driver.findElement(By.xpath("//*[@type='text']")); } })); Assert.assertEquals("Watermelons are so sweet this year!", textInputBox.getAttribute("value"));
Boolean containTextFlag = (new WebDriverWait(driver,10).until(new ExpectedCondition<Boolean>() {
@Override public Boolean apply(WebDriver driver) { return driver.findElement(By.xpath("//p")).getText().equals("perfer fruit"); } })); Assert.assertTrue(containTextFlag);
}catch(Exception e){ e.printStackTrace(); } }
判斷頁面元素是否存在 private boolean isElementPresent(By by){ try{ driver.findElement(by); return true; }catch(Exception e){ return false; }
}
@Test public void testIsElementPresent(){ driver.get("http://www.sogou.com"); if(isElementPresent(By.id("query"))){ WebElement searchInputBox = driver.findElement(By.id("query")); if(searchInputBox.isEnabled()){ searchInputBox.sendKeys("元始金章"); } }else{ Assert.fail("元素沒有找到,zz"); } }