如何在 Selenium 中以程式設計方式停止 firefox 程式載入頁面?


我們可以以程式設計方式停止 Firefox 中的頁面載入。這可以透過首先使用 pageLoadTimeout 方法設定頁面載入時間來實現。

等待頁面載入的時間作為引數傳遞給該方法。

語法

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.MILLISECONDS);

藉助Javascript 執行器強制頁面停止載入。Selenium 使用executeScript方法執行 JavaScript 命令(window.stop() 停止頁面載入)。

語法

((JavascriptExecutor)driver).executeScript("window.stop();");

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StopPageLdWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
      "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //apply page load time
      driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS);
      driver.get("https://tutorialspoint.tw/index.htm");
      for (int i = 0; i < 2; i++) {
         try {
            // launch page
            driver.get("https://tutorialspoint.tw/index.htm");
            break;
         } catch (org.openqa.selenium.TimeoutException e) {
            //stopping page load
            ((JavascriptExecutor)driver)
            .executeScript("window.stop();");
            System.out.println("Page didnot load");
         }
      }
   }
}

輸出

瀏覽器視窗

更新日期:02-Feb-2021

395 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.