• Selenium Video Tutorials

Selenium WebDriver - 顯式/隱式等待



Selenium WebDriver 可以與顯式等待和隱式等待結合使用以實現同步。等待主要用於測試中,以處理動態網頁。

網頁完全載入並 web 元素完全可用之前,通常存在一些延遲時間。Selenium WebDriver 中提供的等待機制有助於將測試執行暫停,直到元素以正確的狀態出現在/消失在網頁上。

讓我們討論 Selenium WebDriver 中的一些等待型別:

隱式等待

這是 Selenium 中預設的等待方式。這是一種應用於整個驅動程式會話的全域性等待。預設等待時間為 0,這意味著如果找不到元素,將立即丟擲錯誤。但是,如果設定了等待時間,則在等待時間超過後將丟擲錯誤。一旦識別出元素,就會返回其引用,並且執行將移至下一步。我們應該以最佳方式使用隱式等待,較長的等待時間會增加測試的執行時間。

語法

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

在上面的示例中,將在 15 秒後丟擲 NoSuchElementException。

顯式等待

它類似於新增到程式碼中的迴圈,這些迴圈輪詢網頁以使特定場景在退出迴圈並轉到下一行程式碼之前變為 true。如果在規定的時間內未滿足情況,則會丟擲超時異常。顯式等待使用 ExpectedConditions 和 WebDriverWait 類應用於具有其條件的特定元素。顯式等待的一些預期條件是:

titleContains, alertIsPresent, invisibilityOfElementLocated(By locator), 
titleIs(), invisibilityOfElementWithText(By locator, String s), 
visibilityOf(), textToBePresentInElement(By locator, String s), 
visibilityOfElementLocated(By locator), visibilityOfAllElements(), 
presenceOfAllElementsLocatedBy(By locator), 
presenceOfElementLocated(By locator), 
elementToBeClickable(By locator), stalenessOf(WebElement e),  
textToBePresentInElementValue(), textToBePresentInElementLocated(), 
elementSelectionStateToBe(), elementToBeSelected(), 
frameToBeAvaliableAndSwitchToIt().

在同一個驅動程式會話中新增隱式等待和顯式等待時,我們應該謹慎,例如,將 15 秒的顯式等待和 10 秒的隱式等待組合在一起可能會導致在 20 秒後發生超時。

語法

WebDriverWait wt = new WebDriverWait(driver,5);
wt.until(ExpectedConditions.invisibilityOfElementLocated
   (By.xpath("//*[@class='mui−btn']")));

在上面的示例中,如果在指定時間內未滿足元素不可見的預期條件,則將在 5 秒後丟擲 TimeOutException。

讓我們舉個例子,我們將嘗試使用錯誤的 xpath 值識別文字 Selenium - 自動化練習表單 並新增隱式等待。在這種情況下,一旦超時時間過去,我們將收到 NoSuchElementException。

此元素的正確 xpath 為:/html/body/div/header/div[2]/h1。但是,為了獲得異常,我們將在我們的實現中使用不正確的 xpath /html/body/div/header/div[2]/u1

Selenium Explicit Implicit 1

示例

在 Implicitwts.java 類檔案中實現程式碼。

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class Implicitwts {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/selenium/practice/selenium_automation_practice.php");

      // identify element with incorrect xpath value
      WebElement l = driver.findElement(By.xpath("/html/body/div/header/div[2]/u1"));
      l.click();

      // get text
      System.out.println("Get text : " + l.getText());

      // Quitting browser
      driver.quit();
   }
}

輸出

Exception in thread "main" 
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: 
{"method":"xpath","selector":"/html/body/div/header/div[2]/u1"}
  (Session info: chrome=121.0.6167.160)
For documentation on this error, please visit: 
https://selenium.programming.tw/documentation/webdriver/troubleshooting/errors#no-such-element-exception

Process finished with exit code 1

在上面的示例中,由於使用了不正確的 xpath 值來識別元素,因此我們收到了 NoSuchElementException。在 2 秒的隱式等待時間過去後,丟擲了異常。

最後,收到訊息 Process finished with exit code 1,表示程式碼執行失敗。

讓我們再舉一個例子,我們將看到在顯式等待時間過去時會丟擲超時異常。

示例

在 Explicitwt.java 類檔案中實現程式碼。

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class Explicitwt {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // launching a browser and open a URL
      driver.get("https://tutorialspoint.tw/index.htm");

      // identify element with locator xpath
      WebElement l = driver.findElement
         (By.xpath("/html/body/header/nav/ul/li[2]/a"));

      // explicit wait 2 secs for presence of incorrect element
      WebDriverWait wt = new WebDriverWait(driver, Duration.ofSeconds(2));
      wt.until(ExpectedConditions.presenceOfElementLocated
         (By.xpath("/html/body/header/nav/ul/li[2]/li")));

      // get text after presence of element condition is met
      System.out.println("Get text : " + l.getText());

      // Quitting browser
      driver.quit();
   }
}

輸出

Exception in thread "main" org.openqa.selenium.TimeoutException: 
   Expected condition failed: waiting for presence of element located by: 
   By.xpath: /html/body/header/nav/ul/li[2]/li (tried for 2 second(s) 
   with 500 milliseconds interval)
   at org.openqa.selenium.support.ui.WebDriverWait.
      timeoutException(WebDriverWait.java:84)
   at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:230)
   at org.example.Explicitwt.main(Explicitwt.java:25)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: 
   Unable to locate element: 
{"method":"xpath","selector":"/html/body/header/nav/ul/li[2]/li"}
  (Session info: chrome=121.0.6167.85)

在上面的示例中,由於在 2 秒的顯式等待時間內未滿足元素存在的預期條件,因此我們收到了 TimeOutException。在 2 秒的顯式等待時間過去後,丟擲了異常。

最後,收到訊息 Process finished with exit code 1,表示程式碼執行失敗。

在本教程中,我們討論瞭如何使用 Selenium WebDriver 處理隱式等待和顯式等待。

廣告
© . All rights reserved.