如何在 Selenium WebDriver 中設定頁面載入的真實超時時間?


我們可以在 Selenium webdriver 中設定頁面載入的真實超時時間。有多種方法可以實現超時。它們列在下面 -

  • setScriptTimeout。

  • pageLoadTimeout。

  • implicitlyWait。

**setScriptTimeout** 方法用於為 webdriver 設定時間。這通常用於非同步測試,在丟擲異常之前完成。超時的預設值為 0。

此方法通常用於 Selenium 中的 **JavaScript** 命令。如果我們省略了為指令碼設定時間,則 **executeAsyncScript** 方法可能會由於 JavaScript 完成執行花費更多時間而導致失敗。

如果超時時間設定為負數,則 JavaScript 可以無限期執行。

語法

driver.manage().timeouts().setScriptTimeout(5,TimeUnit.SECONDS);

**pageLoadTimeout** 方法用於設定整個頁面載入時間,在丟擲異常之前。如果超時時間設定為負數,則載入頁面所需的時間是無限的。

此超時通常與 **navigate** 和 **manage** 方法一起使用。

語法

driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);

示例

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageLoadWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set time for page load
      driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      driver.quit();
   }
}

**implicitlyWait** 是應用於 webdriver 的方法,用於等待頁面中元素可用。它是對每個元素的全域性等待。如果在等待時間過後元素仍然不可用,則會丟擲 **NoSuchElementException**。

語法

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

示例

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      driver.quit();
   }
}

更新於: 2021年2月1日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告