瀏覽器選項

這些功能是所有瀏覽器共用的。

在 Selenium 3 中,功能是透過使用 Desired Capabilities 類別在會話中定義的。從 Selenium 4 開始,您必須使用瀏覽器選項類別。對於遠端驅動程式會話,需要瀏覽器選項實例,因為它決定將使用哪個瀏覽器。

這些選項在 w3c 規範的 Capabilities 中描述。

每個瀏覽器都有自訂選項,除了規範中定義的選項外,還可以定義這些選項。

browserName

使用 Options 類別實例時,預設會設定瀏覽器名稱。

	ChromeOptions chromeOptions = new ChromeOptions();
	String name = chromeOptions.getBrowserName();
    options = webdriver.ChromeOptions()
    assert options.capabilities['browserName'] == 'chrome'
      options = Selenium::WebDriver::Options.chrome

browserVersion

此功能是選用的,用於在遠端設定可用的瀏覽器版本。在最新版本的 Selenium 中,如果在系統上找不到該版本,Selenium Manager 將會自動下載 Selenium Manager

	ChromeOptions chromeOptions = new ChromeOptions();
	String version = "latest";
	chromeOptions.setBrowserVersion(version);
    options = webdriver.ChromeOptions()
    options.browser_version = 'stable'
    assert options.capabilities['browserVersion'] == 'stable'
      options.browser_version = 'latest'

pageLoadStrategy

有三種類型的頁面載入策略可用。

頁面載入策略查詢 document.readyState,如下表所述

策略就緒狀態註解
normalcomplete預設使用,等待所有資源下載完成
eagerinteractiveDOM 存取已就緒,但其他資源(如圖像)可能仍在載入
noneAny完全不封鎖 WebDriver

文件的 document.readyState 屬性描述目前文件的載入狀態。

當透過 URL 導航到新頁面時,預設情況下,WebDriver 會暫停完成導航方法(例如,driver.navigate().get()),直到文件就緒狀態為 complete。這不一定表示頁面已完成載入,尤其是對於像單頁應用程式這樣的網站,它們使用 JavaScript 在就緒狀態返回 complete 後動態載入內容。另請注意,此行為不適用於點擊元素或提交表單所導致的導航。

如果由於下載對自動化不重要的資產(例如,圖像、css、js)而導致頁面載入時間過長,您可以將預設參數 normal 更改為 eagernone 以加快會話速度。此值適用於整個會話,因此請確保您的等待策略足以最大限度地減少不穩定性。

normal (預設)

WebDriver 等待直到 load 事件觸發返回。

移動程式碼

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'normal'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :normal
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('normal'))
      .build();

    await driver.get('https://selenium.dev.org.tw/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

eager

WebDriver 等待直到 DOMContentLoaded 事件觸發返回。

移動程式碼

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'eager'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :eager
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('eager'))
      .build();

    await driver.get('https://selenium.dev.org.tw/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

none

WebDriver 僅等待直到初始頁面下載完成。

移動程式碼

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'none'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.None;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :none
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('none'))
      .build();

    await driver.get('https://selenium.dev.org.tw/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

platformName

這會識別遠端的作業系統,獲取 platformName 會傳回作業系統名稱。

在雲端供應商中,設定 platformName 會設定遠端的作業系統。

	ChromeOptions chromeOptions = new ChromeOptions();
	String platform = "OS X 10.6";
	chromeOptions.setPlatformName(platform);
    options = webdriver.ChromeOptions()
    options.platform_name = 'any'
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.firefox
      options.platform_name = 'Windows 10'

acceptInsecureCerts

此功能檢查在會話期間導航時是否使用了過期(或)無效的 TLS 憑證

如果此功能設定為 false,則當導航遇到任何網域憑證問題時,將會傳回不安全的憑證錯誤。如果設定為 true,瀏覽器將會信任無效的憑證。

預設情況下,此功能將信任所有自我簽署的憑證。一旦設定,acceptInsecureCerts 功能將在整個會話中生效。

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setAcceptInsecureCerts(true);
    options = webdriver.ChromeOptions()
    options.accept_insecure_certs = True
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.accept_insecure_certs = true
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setAcceptInsecureCerts(true))
      .build();

timeouts

WebDriver 會話會被強制執行一定的 會話逾時 間隔,在此期間,使用者可以控制執行腳本或從瀏覽器檢索資訊的行為。

每個會話逾時都配置了不同 timeouts 的組合,如下所述

Script Timeout

指定何時中斷目前瀏覽上下文中正在執行的腳本。當 WebDriver 建立新會話時,會強制執行預設逾時 30,000

	ChromeOptions chromeOptions = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setScriptTimeout(duration);
    options = webdriver.ChromeOptions()
    options.timeouts = { 'script': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {script: 40_000}

Page Load Timeout

指定網頁需要在目前瀏覽上下文中載入的時間間隔。當 WebDriver 建立新會話時,會強制執行預設逾時 300,000。如果頁面載入限制了給定/預設時間範圍,腳本將會被 TimeoutException 停止。

	ChromeOptions chromeOptions = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setPageLoadTimeout(duration);
    options = webdriver.ChromeOptions()
    options.timeouts = { 'pageLoad': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {page_load: 400_000}

Implicit Wait Timeout

這指定了在定位元素時,隱式元素定位策略的等待時間。當 WebDriver 建立新會話時,會強制執行預設逾時 0

	ChromeOptions chromeOptions = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setImplicitWaitTimeout(duration);
    options = webdriver.ChromeOptions()
    options.timeouts = { 'implicit': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {implicit: 1}

unhandledPromptBehavior

指定目前會話的 使用者提示處理程式 的狀態。預設為 關閉並通知狀態

User Prompt Handler

這定義了當在遠端遇到使用者提示時必須採取的動作。這由 unhandledPromptBehavior 功能定義,並具有以下狀態

  • dismiss
  • accept
  • dismiss and notify
  • accept and notify
  • ignore
	ChromeOptions chromeOptions = new ChromeOptions();
	chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);
    options = webdriver.ChromeOptions()
    options.unhandled_prompt_behavior = 'accept'
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.unhandled_prompt_behavior = :accept

setWindowRect

指示遠端是否支援所有調整大小和重新定位 命令

   	ChromeOptions chromeOptions = new ChromeOptions();
   	chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT, true);
    options = webdriver.FirefoxOptions()
    options.set_window_rect = True # Full support in Firefox
    driver = webdriver.Firefox(options=options)
      options = Selenium::WebDriver::Options.firefox
      options.set_window_rect = true

strictFileInteractability

這個新功能指示是否應將嚴格的互動性檢查應用於 input type=file 元素。由於預設情況下嚴格的互動性檢查是關閉的,因此在使用隱藏檔案上傳控制項的 Element Send Keys 時,行為會有所改變。

    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY, true);
    options = webdriver.ChromeOptions()
    options.strict_file_interactability = True
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.strict_file_interactability = true

proxy

代理伺服器充當客戶端和伺服器之間請求的中介。簡單來說,流量會透過代理伺服器流向您請求的位址並返回。

使用 Selenium 的自動化腳本的代理伺服器可能對以下方面有幫助

  • 捕獲網路流量
  • 模擬網站發出的後端呼叫
  • 在複雜的網路拓撲或嚴格的公司限制/政策下存取所需的網站。

如果您在公司環境中,並且瀏覽器無法連線到 URL,則很可能是因為環境需要透過代理伺服器才能存取。

Selenium WebDriver 提供了一種代理設定的方式

移動程式碼

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ProxyTest {
  public static void main(String[] args) {
    Proxy proxy = new Proxy();
    proxy.setHttpProxy("<HOST:PORT>");
    ChromeOptions options = new ChromeOptions();
    options.setCapability("proxy", proxy);
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com/");
    driver.manage().window().maximize();
    driver.quit();
  }
}
    options = webdriver.ChromeOptions()
    options.proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy' : 'http.proxy:1234'})
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

public class ProxyTest{
public static void Main() {
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = "<HOST:PORT>";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://selenium.dev.org.tw/");
}
}
      options = Selenium::WebDriver::Options.chrome
      options.proxy = Selenium::WebDriver::Proxy.new(http: 'myproxy.com:8080')
let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let proxy = require('selenium-webdriver/proxy');
let opts = new chrome.Options();

(async function example() {
opts.setProxy(proxy.manual({http: '<HOST:PORT>'}));
let driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get("https://selenium.dev.org.tw");
}
finally {
await driver.quit();
}
}());
import org.openqa.selenium.Proxy
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

class proxyTest {
fun main() {

        val proxy = Proxy()
        proxy.setHttpProxy("<HOST:PORT>")
        val options = ChromeOptions()
        options.setCapability("proxy", proxy)
        val driver: WebDriver = ChromeDriver(options)
        driver["https://www.google.com/"]
        driver.manage().window().maximize()
        driver.quit()
    }
}
上次修改時間 2024 年 10 月 28 日:更新 Python Options 範例 (#2010)[部署網站] (8deef6c7de9)