java selenium智能等待頁面載入完成範例程式碼_實用技巧

來源:互聯網
上載者:User

java selenium  智能等待頁面載入完成

我們經常會碰到用selenium操作頁面上某個元素的時候, 需要等待頁面載入完成後, 才能操作。  否則頁面上的元素不存在,會拋出異常。 

或者碰到AJAX非同步載入,我們需要等待元素載入完成後, 才能操作

selenium 中提供了非常簡單,智能的方法,來判斷元素是否存在. 

閱讀目錄

  1. 執行個體要求
  2. 隱式等待
  3. 顯式等待

執行個體要求

執行個體:set_timeout.html 下面的html 代碼,  點擊click 按鈕5秒後, 頁面上會出現一個紅色的div快, 我們需要寫一段自動化指令碼智能的去判斷這個div是否存在, 然後把這個div 然後高亮。

<html> <head>  <title>Set Timeout</title>  <style>   .red_box {background-color: red; width = 20%; height: 100px; border: none;}  </style>  <script>   function show_div(){    setTimeout("create_div()", 5000);   }    function create_div(){    d = document.createElement('div');    d.className = "red_box";    document.body.appendChild(d);   }  </script> </head> <body>  <button id = "b" onclick = "show_div()">click</button> </body></html>

隱式等待

  WebDriver driver = new FirefoxDriver();  driver.get("file:///C:/Users/Tank/Desktop/set_timeout.html");     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);  WebElement element = driver.findElement(By.cssSelector(".red_box"));    ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element); 

其中

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

意思是, 總共等待10秒, 如果10秒後,元素還不存在,就會拋出異常  org.openqa.selenium.NoSuchElementException

顯式等待

顯式等待 使用ExpectedConditions類中內建方法, 可以進行顯試等待的判斷。

顯式等待可以自訂等待的條件,用於更加複雜的頁面等待條件

等待的條件

WebDriver方法

頁面元素是否在頁面上可用和可被單擊

elementToBeClickable(By locator)

頁面元素處於被選中狀態

elementToBeSelected(WebElement element)

頁面元素在頁面中存在

presenceOfElementLocated(By locator)

在頁面元素中是否包含特定的文本

textToBePresentInElement(By locator)

頁面元素值

textToBePresentInElementValue(By locator, java.lang.String text)

標題 (title)

titleContains(java.lang.String title)

只有滿足顯式等待的條件滿足,測試代碼才會繼續向後執行後續的測試邏輯

如果超過設定的最大顯式等待時間閾值, 這測試程式會拋出異常。

public static void testWait2(WebDriver driver) {  driver.get("E:\\StashFolder\\huoli_28@hotmail.com\\Stash\\Tank-MoneyProject\\浦東軟體園培訓中心\\我的教材\\Selenium Webdriver\\set_timeout.html");     WebDriverWait wait = new WebDriverWait(driver, 20);  wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".red_box")));  WebElement element = driver.findElement(By.cssSelector(".red_box"));    ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element);  }

以上就是對Java selenium 等待頁面載入的資料整理,後續繼續補充相關資料,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.