这是本节的多页打印视图。 点击此处打印.

返回本页常规视图.

支持的浏览器列表

每个浏览器都有定制和特有的功能。

1 - Chrome 特定功能

特定于 Google Chrome 浏览器的功能和特性.

默认情况下,Selenium 4与Chrome v75及更高版本兼容. 但是请注意Chrome浏览器的版本与chromedriver的主版本需要匹配.

Options

所有浏览器的通用功能请看这 Options page.

Chrome浏览器的特有功能可以在谷歌的页面找到: Capabilities & ChromeOptions

基于默认选项的Chrome浏览器会话看起来是这样:

    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

下面是一些不同功能的常见示例:

参数

args 参数用于启动浏览器时要使用的命令行开关列表. 有两个很好的资源可以用于研究这些参数:

常用的参数包括 --start-maximized, --headless=new 以及 --user-data-dir=...

向选项添加参数:

    options.addArguments("--start-maximized");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_argument("--start-maximized")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddArgument("--start-maximized");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.args << '--start-maximized'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

从指定位置启动浏览器

binary 参数接收一个使用浏览器的备用路径,通过这个参数你可以使用chromedriver 去驱动各种基于Chromium 内核的浏览器.

添加一个浏览器地址到选项中:

    options.setBinary(getChromeLocation());
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.binary_location = chrome_bin
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.BinaryLocation = GetChromeLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.binary = chrome_location
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

添加扩展程序

extensions 参数接受crx文件. 至于解压的目录, 请使用 load-extension 参数代替, 正如 这篇文章 所示.

添加一个扩展程序到选项中:

    options.addExtensions(extensionFilePath);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_extension(extension_file_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddExtension(extensionFilePath);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.add_extension(extension_file_path)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

保持浏览器的打开状态

detach 参数设置为true将在驱动过程结束后保持浏览器的打开状态.

添加一个布尔值到选项中:

Note: This is already the default behavior in Java.

    options.add_experimental_option("detach", True)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options

Note: This is already the default behavior in .NET.

      options.detach = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

排除的参数

Chrome 添加了各种参数,如果你不希望添加某些参数,可以将其传入 excludeSwitches. 一个常见的例子是重新打开弹出窗口阻止程序. 默认参数的完整列表可以参考 Chromium 源码

设置排除参数至选项中:

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddExcludedArgument("disable-popup-blocking");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.exclude_switches << 'disable-popup-blocking'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();
Show full example
const Chrome = require('selenium-webdriver/chrome');
const { Browser, Builder } = require("selenium-webdriver");
const options = new Chrome.Options();



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  xit('Start browser from specified location ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Basic Chrome test', async function () {
    const Options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    const options = new Chrome.Options();
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});

服务

创建默认 Service 对象的示例, 以及用于设置驱动程序位置和端口 可以参考 驱动服务 页面.

日志输出

获取驱动程序日志有助于调试问题. 使用 Service 类, 可以指明日志的路径. 除非用户将其定向到某个位置, 否则将忽略日志记录输出.

文件输出

更改日志记录输出以保存到特定文件:

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java 还允许通过系统属性设置文件输出:
属性键: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
属性值: 表示日志文件路径的字符串

Selenium v4.11

    service = webdriver.ChromeService(log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            service.LogPath = GetLogLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}

Selenium v4.10

      service.log = file_name
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

命令行输出

更改日志记录输出以在控制台中显示为标准输出:

Selenium v4.10

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java 还允许通过系统属性设置控制台输出;
属性键: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
属性值: DriverService.LOG_STDOUTDriverService.LOG_STDERR

Selenium v4.11

    service = webdriver.ChromeService(log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options

$stdout and $stderr are both valid values

Selenium v4.10

      service.log = $stdout
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志级别

共有六种日志级别: ALL, DEBUG, INFO, WARNING, SEVERE, 以及 OFF. 注意 --verbose 等效于 --log-level=ALL 以及 --silent 等效于 --log-level=OFF, 因此, 此示例只是通用地设置日志级别:

Selenium v4.8

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java 还允许通过系统属性设置日志级别:
属性键: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
属性值: ChromiumDriverLogLevel 枚举的字面值

Selenium v4.11

    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options

Selenium v4.10

      service.args << '--log-level=DEBUG'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志文件功能

有 2 个功能仅在写入文件时可用:

  • 追加日志
  • 可读时间戳

要使用它们, 您还需要显式指定日志路径和日志级别. 日志输出将由驱动程序管理, 而不是由进程管理, 因此可能会看到细微的差异.

Selenium v4.8

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java 还允许通过系统属性切换这些功能:
属性键: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY 以及 ChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
属性值: "true""false"

    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options

Selenium v4.8

      service.args << '--append-log'
      service.args << '--readable-timestamp'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

禁用构建检查

Chromedriver 和 Chrome 浏览器版本应该匹配, 如果它们不匹配, 驱动程序将出错. 如果您停用构建检查功能, 则可以强制将驱动程序与任何版本的 Chrome 一起使用. 请注意, 这是一项不受支持的功能, 并且不会调查 bug.

Selenium v4.8

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java 还允许通过系统属性禁用构建检查:
属性键: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
属性值: "true""false"

Selenium v4.11

    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
            service.DisableBuildCheck = true;
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class ChromeTest
    {
        private ChromeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new ChromeOptions();
            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new ChromeOptions();

            options.AddArgument("--start-maximized");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new ChromeOptions();

            options.BinaryLocation = GetChromeLocation();

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new ChromeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new ChromeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new ChromeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new ChromeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = ChromeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting ChromeDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = ChromeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new ChromeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new ChromeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = ChromeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new ChromeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetChromeLocation()
        {
            var options = new ChromeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}

Selenium v4.8

      service.args << '--disable-build-check'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

特殊功能

Casting

你可以驱动 Chrome Cast 设备,包括共享选项卡

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

网络条件

您可以模拟各种网络条件.

以下示例适用于本地 webdrivers. 针对远程 webdrivers, 请参考 Remote WebDriver 页面.

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    logs = driver.get_log("browser")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
      logs = @driver.logs.get(:browser)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

权限

    driver.setPermission("camera", "denied");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;


public class ChromeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);
    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    driver = new ChromeDriver(options);
  }

  @Test
  public void arguments() {
    ChromeOptions options = getDefaultChromeOptions();

    options.addArguments("--start-maximized");

    driver = new ChromeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setBinary(getChromeLocation());

    driver = new ChromeDriver(options);
  }

  @Test
  public void extensionOptions() {
    ChromeOptions options = getDefaultChromeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    ChromeOptions options = getDefaultChromeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new ChromeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    ChromeOptions options = getDefaultChromeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(ChromeOptions.LOGGING_PREFS, logPrefs);

    driver = new ChromeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogFile(logLocation).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogOutput(System.out).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.DEBUG.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    ChromeDriverService service =
        new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new ChromeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getChromeLocation() {
    ChromeOptions options = getDefaultChromeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermission() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new ChromeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((ChromeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((ChromeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
        () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
        () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
        () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
        () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((ChromeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    ChromeDriver driver = new ChromeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    driver.set_permissions('camera', 'denied')
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_chrome_options()
    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_args():
    options = get_default_chrome_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(chrome_bin):
    options = get_default_chrome_options()

    options.binary_location = chrome_bin

    driver = webdriver.Chrome(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_chrome_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Chrome(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_chrome_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_chrome_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Chrome(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.ChromeService(log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting ChromeDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.ChromeService(log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert "Starting ChromeDriver" in out

    driver.quit()


def test_log_level(capfd):
    service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    out, err = capfd.readouterr()
    assert '[DEBUG]' in err

    driver.quit()


def test_log_features(log_path):
    service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Chrome(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(capfd):
    service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)

    driver = webdriver.Chrome(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    out, err = capfd.readouterr()
    assert expected in err

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Chrome()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Chrome()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Chrome()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Chrome' do
  describe 'Options' do
    let(:chrome_location) { driver_finder && ENV.fetch('CHROME_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.chrome
      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.chrome

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.chrome

      options.binary = chrome_location

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.chrome

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :chrome, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.chrome

      options.detach = true

      @driver = Selenium::WebDriver.for :chrome, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.chrome

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :chrome, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('chromedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.chrome

      service.log = file_name

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).first).to include('Starting ChromeDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.chrome

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :chrome, service: service
      }.to output(/Starting ChromeDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.chrome
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :chrome, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.chrome(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :chrome, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.chrome log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :chrome, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :chrome
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :chrome
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.chrome(browser_version: 'stable')
    service = Selenium::WebDriver::Service.chrome
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['CHROMEDRIVER_BIN'] = finder.driver_path
    ENV['CHROME_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                 'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

DevTools

详见 Chrome DevTools 部分以获取有关使用Chrome DevTools的更多信息

2 - Edge 特定功能

这些是特定于微软Edge浏览器的功能和特性.

微软Edge是用Chromium实现的, 最早支持版本是v79. 与Chrome类似, Edge驱动的主版本号必须与Edge浏览器的主要版本匹配.

Chrome 页面 上找到的所有capabilities和选项也适用于Edge.

选项

所有浏览器的共有功能在 Options 页面.

Chromium独有的功能记录在谷歌的 Capabilities & ChromeOptions

使用基本定义的选项启动 Edge 会话如下所示:

    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
    let options = new edge.Options();
    driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options)
      .build();
Show full example
const {Browser, Builder} = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');


describe('Open Edge', function () {
  let driver;



  before(async function () {
    let options = new edge.Options();
    driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options)
      .build();
  });

  after(async () => await driver.quit());

  it('Basic Edge test', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  });
});

参数

args 参数用于列出启动浏览器时使用的命令行开关. 有两个很好的资源可用于研究这些参数:

常用参数包括 --start-maximized--headless=new--user-data-dir=...

为options添加参数:

    options.addArguments("--start-maximized");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_argument("--start-maximized")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddArgument("--start-maximized");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.args << '--start-maximized'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
      .setEdgeOptions(options.addArguments('--headless=new'))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  it('Basic edge test', async function () {
    const Options = new edge.Options();
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    let injected = await driver.findElement(By.id('webextensions-selenium-example'));
    assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
    await driver.quit();
  });
});

在指定位置启动浏览器

binary 参数包含要使用的浏览器备用位置的路径. 使用此参数, 您可以使用 chromedriver 驱动各种基于 Chromium 的浏览器.

在options中添加浏览器位置:

    options.setBinary(getEdgeLocation());
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.binary_location = edge_bin
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.BinaryLocation = GetEdgeLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.binary = edge_location
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

添加扩展

extensions参数接受 crx 文件. 至于已解压的目录、中提到, 请使用本文中提及的 load-extension.

在options中添加扩展:

    options.addExtensions(extensionFilePath);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_extension(extension_file_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddExtension(extensionFilePath);
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.add_extension(extension_file_path)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
      .setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  it('Basic edge test', async function () {
    const Options = new edge.Options();
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    let injected = await driver.findElement(By.id('webextensions-selenium-example'));
    assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
    await driver.quit();
  });
});

保持浏览器打开

detach 参数设置为 true后, 只要不向driver发送退出命令, 就可以在进程结束后保持浏览器打开.

Note: This is already the default behavior in Java.

    options.add_experimental_option("detach", True)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options

Note: This is already the default behavior in .NET.

      options.detach = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
      .setEdgeOptions(options.detachDriver(true))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  it('Basic edge test', async function () {
    const Options = new edge.Options();
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    let injected = await driver.findElement(By.id('webextensions-selenium-example'));
    assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
    await driver.quit();
  });
});

排除参数

MSEdgedriver 有几个用于启动浏览器的默认参数. 如果不希望添加这些参数, 可将它们传递到 excludeSwitches 中. 一个常见的例子就是重新打开弹出窗口拦截器. 默认参数的完整列表参考 Chromium Source Code

在options中设置排除参数:

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            options.AddExcludedArgument("disable-popup-blocking");
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.exclude_switches << 'disable-popup-blocking'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end
      .setEdgeOptions(options.excludeSwitches('enable-automation'))
Show full example
const {Browser, By, Builder } = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
const assert = require("assert");



describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addArguments('--headless=new'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('exclude switches', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.excludeSwitches('enable-automation'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Keep browser open - set detach to true ', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.detachDriver(true))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // As tests runs in ci, quitting the driver instance to avoid any failures
    await driver.quit();
  });

  it('Basic edge test', async function () {
    const Options = new edge.Options();
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(Options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Add Extension', async function () {
    let driver = new Builder()
      .forBrowser(Browser.EDGE)
      .setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    let injected = await driver.findElement(By.id('webextensions-selenium-example'));
    assert.equal(await injected.getText(), `Content injected by webextensions-selenium-example`)
    await driver.quit();
  });
});

服务

创建默认服务对象, 设置驱动程序位置和端口的示例可以参考 Driver服务 页面.

日志输出

获取驱动程序日志有助于调试问题。 服务类可让您配置日志的输出。 日志输出会被忽略, 除非用户显示指定.

文件输出

更改日志输出以保存到特定文件:

Selenium v4.10

    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java同样允许在系统属性中配置文件输出:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: String representing path to log file

    service = webdriver.EdgeService(log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            service.LogPath = GetLogLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}

Selenium v4.10

      service.log = file_name
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

控制台输出

要更改日志输出, 使其在控制台中显示为标准输出:

Selenium v4.10

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java同样允许在系统属性中配置控制台输出:
属性键: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
属性值: DriverService.LOG_STDOUTDriverService.LOG_STDERR

Selenium v4.11

    service = webdriver.EdgeService(log_output=subprocess.STDOUT)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options

$stdout and $stderr are both valid values

Selenium v4.10

      service.log = $stdout
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志级别

有 6 种可用的日志级别: ALL, DEBUG, INFO, WARNING, SEVERE, 以及 OFF. 请注意, --verbose 等同于 --log-level=ALL , 而 --silent 等同于 --log-level=OFF, 因此, 本例只是一般性地设置日志级别:

Selenium v4.8

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java同样允许在系统属性中配置日志级别:
属性键: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
属性值: String representation of ChromiumDriverLogLevel enum

    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options

Selenium v4.10

      service.args << '--log-level=DEBUG'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志文件功能

有 2 项功能只有在记录到文件时才可用:

  • 追加日志
  • 可读时间戳

要使用它们, 还需要明确指定日志路径和日志级别. 日志输出将由driver而非进程管理, 因此可能会出现细微差别.

Selenium v4.8

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java同样允许在系统属性中配置开闭这些功能:
属性键: EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY 以及 EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
属性值: "true""false"

    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options

Selenium v4.8

      service.args << '--append-log'
      service.args << '--readable-timestamp'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

禁用构建检查

Edge 浏览器和 msedgedriver 版本应该匹配, 如果不匹配, 驱动程序就会出错. 如果禁用构建检查, 则可以强制驱动程序与任何版本的 Edge 一起使用. 请注意, 这是一项不受支持的功能, 而且不会对错误进行调查.

Selenium v4.8

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}

注意: Java同样允许在系统属性中配置禁用构建检查:
属性键: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
属性值: "true""false"

    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
            service.DisableBuildCheck = true;
Show full example
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class EdgeTest
    {
        private EdgeDriver driver;
        private string _logLocation;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new EdgeOptions();
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new EdgeOptions();

            options.AddArgument("--start-maximized");
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void SetBrowserLocation()
        {
            var options = new EdgeOptions();

            options.BinaryLocation = GetEdgeLocation();
    
            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void InstallExtension()
        {
            var options = new EdgeOptions();
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");

            options.AddExtension(extensionFilePath);

            driver = new EdgeDriver(options);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";

            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void ExcludeSwitch()
        {
            var options = new EdgeOptions();

            options.AddExcludedArgument("disable-popup-blocking");

            driver = new EdgeDriver(options);
        }

        [TestMethod]
        public void LogsToFile()
        {
            var service = EdgeDriverService.CreateDefaultService();

            service.LogPath = GetLogLocation();

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = EdgeDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            driver = new EdgeDriver(service);

            Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsLevel()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();

            // service.LogLevel = ChromiumDriverLogLevel.Debug 

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void ConfigureDriverLogs()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.EnableAppendLog = true;
            // service.readableTimeStamp = true;

            driver = new EdgeDriver(service);

            driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
            Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
        }

        [TestMethod]
        public void DisableBuildCheck()
        {
            var service = EdgeDriverService.CreateDefaultService();
            service.LogPath = GetLogLocation();
            service.EnableVerboseLogging = true;

            service.DisableBuildCheck = true;

            driver = new EdgeDriver(service);
            driver.Quit(); // Close the Service log file before reading
            var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
        }
        
        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private static string GetEdgeLocation()
        {
            var options = new EdgeOptions
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}

Selenium v4.8

      service.args << '--disable-build-check'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

Internet Explorer 兼容模式

微软Edge可以被"Internet Explorer兼容模式"驱动, 该模式使用Internet Explorer驱动类与微软Edge结合使用. 阅读 Internet Explorer 页面 了解更多详情.

特殊功能

某些浏览器实现了其特有的附加功能.

Cast

您可以使用 Edge 驱动 Chrome Cast 设备, 包括共享标签页

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

网络状况

您可以模拟各种网络状况.


    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

日志

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    logs = driver.get_log("browser")
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
      logs = @driver.logs.get(:browser)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

权限

    driver.setPermission("camera", "denied");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.chromium.ChromiumNetworkConditions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.logging.*;
import org.openqa.selenium.remote.service.DriverFinder;



public class EdgeTest extends BaseTest {
  @AfterEach
  public void clearProperties() {
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);
    System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);
  }

  @Test
  public void basicOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    driver = new EdgeDriver(options);
  }

  @Test
  public void arguments() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.addArguments("--start-maximized");

    driver = new EdgeDriver(options);
  }

  @Test
  public void setBrowserLocation() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setBinary(getEdgeLocation());

    driver = new EdgeDriver(options);
  }

  @Test
  public void extensionOptions() {
    EdgeOptions options = getDefaultEdgeOptions();
    Path path = Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");
    File extensionFilePath = new File(path.toUri());

    options.addExtensions(extensionFilePath);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  @Test
  public void excludeSwitches() {
    EdgeOptions options = getDefaultEdgeOptions();

    options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));

    driver = new EdgeDriver(options);
  }

  @Test
  public void loggingPreferences() {
    EdgeOptions options = getDefaultEdgeOptions();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    options.setCapability(EdgeOptions.LOGGING_PREFS, logPrefs);

    driver = new EdgeDriver(options);
    driver.get("https://www.selenium.dev");

    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
    Assertions.assertFalse(logEntries.getAll().isEmpty());
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
  }

  @Test
  public void configureDriverLogs() throws IOException {
    File logLocation = getTempFile("configureDriverLogs", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY, ChromiumDriverLogLevel.DEBUG.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
    Assertions.assertTrue(pattern.matcher(fileContent).find());
  }

  @Test
  public void disableBuildChecks() throws IOException {
    File logLocation = getTempFile("disableBuildChecks", ".log");
    System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
        ChromiumDriverLogLevel.WARNING.toString());

    EdgeDriverService service =
        new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();

    driver = new EdgeDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    String expected =
        "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
    Assertions.assertTrue(fileContent.contains(expected));
  }

  private File getEdgeLocation() {
    EdgeOptions options = getDefaultEdgeOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(EdgeDriverService.createDefaultService(), options);
    return new File(finder.getBrowserPath());
  }

  @Test
  public void setPermissions() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev");

    driver.setPermission("camera", "denied");

    // Verify the permission state is 'denied'
    String script = "return navigator.permissions.query({ name: 'camera' })" +
            "    .then(permissionStatus => permissionStatus.state);";
    String permissionState = (String) driver.executeScript(script);

    Assertions.assertEquals("denied", permissionState);
    driver.quit();
  }

  @Test
  public void setNetworkConditions() {
    driver = new EdgeDriver();

    ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
    networkConditions.setOffline(false);
    networkConditions.setLatency(java.time.Duration.ofMillis(20)); // 20 ms of latency
    networkConditions.setDownloadThroughput(2000 * 1024 / 8); // 2000 kbps
    networkConditions.setUploadThroughput(2000 * 1024 / 8);   // 2000 kbps

    ((EdgeDriver) driver).setNetworkConditions(networkConditions);

    driver.get("https://www.selenium.dev");

    // Assert the network conditions are set as expected
    ChromiumNetworkConditions actualConditions = ((EdgeDriver) driver).getNetworkConditions();
    Assertions.assertAll(
            () -> Assertions.assertEquals(networkConditions.getOffline(), actualConditions.getOffline()),
            () -> Assertions.assertEquals(networkConditions.getLatency(), actualConditions.getLatency()),
            () -> Assertions.assertEquals(networkConditions.getDownloadThroughput(), actualConditions.getDownloadThroughput()),
            () -> Assertions.assertEquals(networkConditions.getUploadThroughput(), actualConditions.getUploadThroughput())
    );
    ((EdgeDriver) driver).deleteNetworkConditions();
    driver.quit();
  }

  @Test
  public void castFeatures() {
    EdgeDriver driver = new EdgeDriver();

    List<Map<String, String>> sinks = driver.getCastSinks();
    if (!sinks.isEmpty()) {
      String sinkName = sinks.get(0).get("name");
      driver.startTabMirroring(sinkName);
      driver.stopCasting(sinkName);
    }

    driver.quit();
  }

  @Test
  public void getBrowserLogs() {
    EdgeDriver driver = new EdgeDriver();
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
    WebElement consoleLogButton = driver.findElement(By.id("consoleError"));
    consoleLogButton.click();

    LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

    // Assert that at least one log contains the expected message
    boolean logFound = false;
    for (LogEntry log : logs) {
      if (log.getMessage().contains("I am console error")) {
        logFound = true;
        break;
      }
    }

    Assertions.assertTrue(logFound, "No matching log message found.");
    driver.quit();
  }
}
    driver.set_permissions('camera', 'denied')
Show full example
import os
import re
import subprocess
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_basic_options():
    options = get_default_edge_options()
    driver = webdriver.Edge(options=options)

    driver.quit()


def test_args():
    options = get_default_edge_options()

    options.add_argument("--start-maximized")

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_set_browser_location(edge_bin):
    options = get_default_edge_options()

    options.binary_location = edge_bin

    driver = webdriver.Edge(options=options)

    driver.quit()


def test_add_extension():
    options = get_default_edge_options()
    extension_file_path = os.path.abspath("tests/extensions/webextensions-selenium-example.crx")

    options.add_extension(extension_file_path)

    driver = webdriver.Edge(options=options)
    driver.get("https://www.selenium.dev/selenium/web/blank.html")

    driver.quit()


def test_keep_browser_open():
    options = get_default_edge_options()

    options.add_experimental_option("detach", True)

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_exclude_switches():
    options = get_default_edge_options()

    options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])

    driver = webdriver.Edge(options=options)
    driver.get('http://selenium.dev')

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.EdgeService(log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as fp:
        assert "Starting Microsoft Edge WebDriver" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.EdgeService(log_output=subprocess.STDOUT)

    driver = webdriver.Edge(service=service)

    out, err = capfd.readouterr()
    assert "Starting Microsoft Edge WebDriver" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert '[DEBUG]' in f.read()

    driver.quit()


def test_log_features(log_path):
    service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    with open(log_path, 'r') as f:
        assert re.match(r"\[\d\d-\d\d-\d\d\d\d", f.read())

    driver.quit()


def test_build_checks(log_path):
    service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)

    driver = webdriver.Edge(service=service)

    expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
    with open(log_path, 'r') as f:
        assert expected in f.read()

    driver.quit()


def test_set_network_conditions():
    driver = webdriver.Edge()

    network_conditions = {
        "offline": False,
        "latency": 20,  # 20 ms of latency
        "download_throughput": 2000 * 1024 / 8,  # 2000 kbps
        "upload_throughput": 2000 * 1024 / 8,    # 2000 kbps
    }
    driver.set_network_conditions(**network_conditions)

    driver.get("https://www.selenium.dev")

    # check whether the network conditions are set
    assert driver.get_network_conditions() == network_conditions

    driver.quit()


def test_set_permissions():
    driver = webdriver.Edge()
    driver.get('https://www.selenium.dev')

    driver.set_permissions('camera', 'denied')

    assert get_permission_state(driver, 'camera') == 'denied'
    driver.quit()


def get_permission_state(driver, name):
    """Helper function to query the permission state."""
    script = """
    const callback = arguments[arguments.length - 1];
    navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
        callback(permissionStatus.state);
    });
    """
    return driver.execute_async_script(script, name)


def test_cast_features():
    driver = webdriver.Edge()

    try:
        sinks = driver.get_sinks()
        if sinks:
            sink_name = sinks[0]['name']
            driver.start_tab_mirroring(sink_name)
            driver.stop_casting(sink_name)
        else:
            pytest.skip("No available Cast sinks to test with.")
    finally:
        driver.quit()


def test_get_browser_logs():
    driver = webdriver.Edge()
    driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")
    driver.find_element(By.ID, "consoleError").click()

    logs = driver.get_log("browser")

    # Assert that at least one log contains the expected message
    assert any("I am console error" in log['message'] for log in logs), "No matching log message found."
    driver.quit()

def get_default_edge_options():
    options = webdriver.EdgeOptions()
    options.add_argument("--no-sandbox")
    return options
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Edge' do
  describe 'Options' do
    let(:edge_location) { driver_finder && ENV.fetch('EDGE_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.edge
      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.edge

      options.args << '--start-maximized'

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.edge

      options.binary = edge_location

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'add extensions' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx', __dir__)
      options = Selenium::WebDriver::Options.edge

      options.add_extension(extension_file_path)

      @driver = Selenium::WebDriver.for :edge, options: options
      @driver.get('https://www.selenium.dev/selenium/web/blank.html')
      injected = @driver.find_element(:id, 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'keeps browser open' do
      options = Selenium::WebDriver::Options.edge

      options.detach = true

      @driver = Selenium::WebDriver.for :edge, options: options
    end

    it 'excludes switches' do
      options = Selenium::WebDriver::Options.edge

      options.exclude_switches << 'disable-popup-blocking'

      @driver = Selenium::WebDriver.for :edge, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { File.expand_path('msedgedriver.log') }

    after { FileUtils.rm_f(file_name) }

    it 'logs to file' do
      service = Selenium::WebDriver::Service.edge

      service.log = file_name

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.edge

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :edge, service: service
      }.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.edge
      service.log = file_name

      service.args << '--log-level=DEBUG'

      @driver = Selenium::WebDriver.for :edge, service: service
      expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
    end

    it 'sets log features' do
      args = ["--log-path=#{file_name}", '--verbose']
      service = Selenium::WebDriver::Service.edge(args: args)

      service.args << '--append-log'
      service.args << '--readable-timestamp'

      @driver = Selenium::WebDriver.for :edge, service: service

      expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
    end

    it 'disables build checks' do
      service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']

      service.args << '--disable-build-check'

      @driver = Selenium::WebDriver.for :edge, service: service
      warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
      expect(File.readlines(file_name).grep(warning).any?).to eq true
    end
  end

  describe 'Special Features' do
    it 'casts' do
      @driver = Selenium::WebDriver.for :edge
      sinks = @driver.cast_sinks
      unless sinks.empty?
        device_name = sinks.first['name']
        @driver.start_cast_tab_mirroring(device_name)
        expect { @driver.stop_casting(device_name) }.not_to raise_exception
      end
    end

    it 'gets and sets network conditions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.network_conditions = {offline: false, latency: 100, throughput: 200}
      expect(@driver.network_conditions).to eq(
        'offline' => false,
        'latency' => 100,
        'download_throughput' => 200,
        'upload_throughput' => 200)
    end

    it 'gets the browser logs' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      sleep 1
      logs = @driver.logs.get(:browser)

      expect(logs.first.message).to include 'Failed to load resource'
    end

    it 'sets permissions' do
      @driver = Selenium::WebDriver.for :edge
      @driver.navigate.to 'https://www.selenium.dev/selenium/web/'
      @driver.add_permission('camera', 'denied')
      @driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
      expect(permission('camera')).to eq('denied')
      expect(permission('clipboard-read')).to eq('denied')
      expect(permission('clipboard-write')).to eq('prompt')
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.edge(browser_version: 'stable')
    service = Selenium::WebDriver::Service.edge
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['EDGEDRIVER_BIN'] = finder.driver_path
    ENV['EDGE_BIN'] = finder.browser_path
  end

  def permission(name)
    @driver.execute_async_script('callback = arguments[arguments.length - 1];' \
                                   'callback(navigator.permissions.query({name: arguments[0]}));', name)['state']
  end
end

开发者工具

有关在 Edge 中使用 DevTools 的更多信息, 请参阅 [Chrome DevTools] 部分.

3 - Firefox specific functionality

These are capabilities and features specific to Mozilla Firefox browsers.

Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver.

Options

Capabilities common to all browsers are described on the Options page.

Capabilities unique to Firefox can be found at Mozilla’s page for firefoxOptions

Starting a Firefox session with basic defined options looks like this:

    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end
    driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options)
      .build();
Show full example
const {Browser, Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');


describe('Open Firefox', function () {
  let driver;

  before(async function () {
    let options = new firefox.Options();
    driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options)
      .build();
  });

  after(async () => await driver.quit());

  it('Basic Firefox test', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  });
});

Here are a few common use cases with different capabilities:

Arguments

The args parameter is for a list of Command line switches used when starting the browser.
Commonly used args include -headless and "-profile", "/path/to/profile"

Add an argument to options:

    options.addArguments("-headless");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    options.add_argument("-headless")
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
            options.AddArgument("-headless");
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.args << '-headless'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end
      .setFirefoxOptions(options.addArguments('--headless'))
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");


describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options.addArguments('--headless'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Should be able to add extension', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });

  it('Should be able to install unsigned addon', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath, true);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });
});

Start browser in a specified location

The binary parameter takes the path of an alternate location of browser to use. For example, with this parameter you can use geckodriver to drive Firefox Nightly instead of the production version when both are present on your computer.

Add a browser location to options:

    options.setBinary(getFirefoxLocation());
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    options.binary_location = firefox_bin
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
            options.BinaryLocation = GetFirefoxLocation();
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      options.binary = firefox_location
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Profiles

There are several ways to work with Firefox profiles

    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
var options = new FirefoxOptions();
var profile = new FirefoxProfile();
options.Profile = profile;
var driver = new RemoteWebDriver(options);
  
      profile = Selenium::WebDriver::Firefox::Profile.new
          profile['browser.download.dir'] = '/tmp/webdriver-downloads'
          options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
Show full example
# frozen_string_literal: true
    
    require 'spec_helper'
    
    RSpec.describe 'Firefox' do
      describe 'Options' do
        let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }
    
        it 'basic options' do
          options = Selenium::WebDriver::Options.firefox
          @driver = Selenium::WebDriver.for :firefox, options: options
        end
    
        it 'add arguments' do
          options = Selenium::WebDriver::Options.firefox
    
          options.args << '-headless'
    
          @driver = Selenium::WebDriver.for :firefox, options: options
        end
    
        it 'sets location of binary' do
          options = Selenium::WebDriver::Options.firefox
    
          options.binary = firefox_location
    
          @driver = Selenium::WebDriver.for :firefox, options: options
        end
      end
    
      describe 'Service' do
        let(:file_name) { Tempfile.new('geckodriver').path }
        let(:root_directory) { Dir.mktmpdir }
    
        after do
          FileUtils.rm_f(file_name)
          FileUtils.rm_rf(root_directory)
        end
    
        it 'logs to file' do
          service = Selenium::WebDriver::Service.firefox
    
          service.log = file_name
    
          @driver = Selenium::WebDriver.for :firefox, service: service
          expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
        end
    
        it 'logs to console' do
          service = Selenium::WebDriver::Service.firefox
    
          service.log = $stdout
    
          expect {
            @driver = Selenium::WebDriver.for :firefox, service: service
          }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
        end
    
        it 'sets log level' do
          service = Selenium::WebDriver::Service.firefox
          service.log = file_name
    
          service.args += %w[--log debug]
    
          @driver = Selenium::WebDriver.for :firefox, service: service
          expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
        end
    
        it 'stops truncating log lines' do
          service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
    
          service.args << '--log-no-truncate'
    
          @driver = Selenium::WebDriver.for :firefox, service: service
          expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
        end
    
        it 'sets default profile location' do
          service = Selenium::WebDriver::Service.firefox
    
          service.args += ['--profile-root', root_directory]
    
          @driver = Selenium::WebDriver.for :firefox, service: service
          profile_location = Dir.new(@driver.capabilities['moz:profile'])
          expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
        end
      end
    
      describe 'Features' do
        let(:driver) { start_firefox }
    
        it 'installs addon' do
          extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
    
          driver.install_addon(extension_file_path)
    
          driver.get 'https://www.selenium.dev/selenium/web/blank.html'
          injected = driver.find_element(id: 'webextensions-selenium-example')
          expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
        end
    
        it 'uninstalls addon' do
          extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
          extension_id = driver.install_addon(extension_file_path)
    
          driver.uninstall_addon(extension_id)
    
          driver.get 'https://www.selenium.dev/selenium/web/blank.html'
          expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
        end
    
        it 'installs unsigned addon' do
          extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)
    
          driver.install_addon(extension_dir_path, true)
    
          driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
          injected = driver.find_element(id: 'webextensions-selenium-example')
          expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
        end
    
        it 'takes full page screenshot' do
          driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
          Dir.mktmpdir('screenshot_test') do |dir|
            screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
    
            expect(screenshot).to be_a File
          end
        end
    
        it 'sets the context' do
          driver.context = 'content'
          expect(driver.context).to eq 'content'
        end
      end
    
      describe 'Profile' do
        it 'creates a new profile' do
          profile = Selenium::WebDriver::Firefox::Profile.new
          profile['browser.download.dir'] = '/tmp/webdriver-downloads'
          options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
          expect(options.profile).to eq(profile)
        end
      end
    
      def driver_finder
        options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
        service = Selenium::WebDriver::Service.firefox
        finder = Selenium::WebDriver::DriverFinder.new(options, service)
        ENV['GECKODRIVER_BIN'] = finder.driver_path
        ENV['FIREFOX_BIN'] = finder.browser_path
      end
    end
    
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');

const options = new firefox.Options();
let profile = '/path to custom profile';
options.setProfile(profile);
const driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxOptions(options)
    .build();
  
val options = FirefoxOptions()
options.profile = FirefoxProfile()
driver = RemoteWebDriver(options)
  

Note: Whether you create an empty FirefoxProfile or point it to the directory of your own profile, Selenium will create a temporary directory to store either the data of the new profile or a copy of your existing one. Every time you run your program, a different temporary directory will be created. These directories are not cleaned up explicitly by Selenium, they should eventually get removed by the operating system. However, if you want to remove the copy manually (e.g. if your profile is large in size), the path of the copy is exposed by the FirefoxProfile object. Check the language specific implementation to see how to retrieve that location.

If you want to use an existing Firefox profile, you can pass in the path to that profile. Please refer to the official Firefox documentation for instructions on how to find the directory of your profile.

Service

Service settings common to all browsers are described on the Service page.

Log output

Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.

File output

To change the logging output to save to a specific file:

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}

Note: Java also allows setting file output by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: String representing path to log file

Selenium v4.11

    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.10

      service.log = file_name
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Console output

To change the logging output to display in the console:

Selenium v4.10

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}

Note: Java also allows setting console output by System Property;
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT or DriverService.LOG_STDERR

Selenium v4.11

    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.10

      service.log = $stdout
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Log level

There are 7 available log levels: fatal, error, warn, info, config, debug, trace. If logging is specified the level defaults to info.

Note that -v is equivalent to -log debug and -vv is equivalent to log trace, so this examples is just for setting the log level generically:

Selenium v4.10

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}

Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of FirefoxDriverLogLevel enum

Selenium v4.11

    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.10

      service.args += %w[--log debug]
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Truncated Logs

The driver logs everything that gets sent to it, including string representations of large binaries, so Firefox truncates lines by default. To turn off truncation:

Selenium v4.10

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}

Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
Property value: "true" or "false"

Selenium v4.11

    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.10

      service.args << '--log-no-truncate'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Profile Root

The default directory for profiles is the system temporary directory. If you do not have access to that directory, or want profiles to be created some place specific, you can change the profile root directory:

Selenium v4.10

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}

Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
Property value: String representing path to profile root directory

    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.8

      service.args += ['--profile-root', root_directory]
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Special Features

Add-ons

Unlike Chrome, Firefox extensions are not added as part of capabilities as mentioned in this issue, they are created after starting the driver.

The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.

Installation

A signed xpi file you would get from Mozilla Addon page

    driver.installExtension(xpiPath);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    driver.install_addon(addon_path_xpi)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      driver.install_addon(extension_file_path)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end
    let id = await driver.installAddon(xpiPath);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");


describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options.addArguments('--headless'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Should be able to add extension', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });

  it('Should be able to install unsigned addon', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath, true);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });
});

Uninstallation

Uninstalling an addon requires knowing its id. The id can be obtained from the return value when installing the add-on.

    driver.uninstallExtension(id);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    driver.uninstall_addon(id)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.5

            driver.UninstallAddOn(extensionId);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}
      driver.uninstall_addon(extension_id)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end
    await driver.uninstallAddon(id);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");


describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options.addArguments('--headless'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Should be able to add extension', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });

  it('Should be able to install unsigned addon', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath, true);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });
});

Unsigned installation

When working with an unfinished or unpublished extension, it will likely not be signed. As such, it can only be installed as “temporary.” This can be done by passing in either a zip file or a directory, here’s an example with a directory:

    driver.installExtension(path, true);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    driver.install_addon(addon_path_dir, temporary=True)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()

Selenium v4.5

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace SeleniumDocs.Browsers
{
    [TestClass]
    public class FirefoxTest
    {
        private FirefoxDriver driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void Arguments()
        {
            var options = new FirefoxOptions();

            options.AddArgument("-headless");

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        public void SetBinary()
        {
            var options = new FirefoxOptions();

            options.BinaryLocation = GetFirefoxLocation();

            driver = new FirefoxDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver	INFO	Listening on")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogToConsole = true;

            driver = new FirefoxDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        [Ignore("You can set it, just can't see it")]
        public void LogsLevel()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.LogFile = _logLocation

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Marionette\tDEBUG")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void StopsTruncatingLogs()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            //service.TruncateLogs = false;

            service.LogLevel = FirefoxDriverLogLevel.Debug;

            driver = new FirefoxDriver(service);
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNull(lines.FirstOrDefault(line => line.Contains(" ... ")));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void SetProfileLocation()
        {
            var service = FirefoxDriverService.CreateDefaultService();
            // service.ProfileRoot = GetTempDirectory();

            driver = new FirefoxDriver(service);

            string profile = (string)driver.Capabilities.GetCapability("moz:profile");
            string[] directories = profile.Split("/");
            var dirName = directories.Last();
            Assert.AreEqual(GetTempDirectory() + "/" + dirName, profile);
        }

        [TestMethod]
        public void InstallAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");

            driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }

        [TestMethod]
        public void UnInstallAddon()
        {
            driver = new FirefoxDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
            string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));

            driver.UninstallAddOn(extensionId);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
        }

        [TestMethod]
        public void InstallUnsignedAddon()
        {
            SetWaitingDriver();
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");

            driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);

            driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
            IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
            Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
        }
        
        private string GetLogLocation()
        {
            if (_logLocation != null && !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath != null && !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private void SetWaitingDriver()
        {
            driver = new FirefoxDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
        }

        private static string GetFirefoxLocation()
        {
            var options = new FirefoxOptions()
            {
                BrowserVersion = "stable"
            };
            return new DriverFinder(options).GetBrowserPath();
        }
    }
}

Selenium v4.5

      driver.install_addon(extension_dir_path, true)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end
    let id = await driver.installAddon(xpiPath, true);
Show full example
const {Browser, By, Builder} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const assert = require("assert");


describe('Should be able to Test Command line arguments', function () {
  it('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .setFirefoxOptions(options.addArguments('--headless'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });

  it('Should be able to add extension', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });

  it('Should be able to install unsigned addon', async function () {

    const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
    let driver = new Builder()
      .forBrowser(Browser.FIREFOX)
      .build()
    let id = await driver.installAddon(xpiPath, true);
    await driver.uninstallAddon(id);


    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    const ele = await driver.findElements(By.id("webextensions-selenium-example"));
    assert.equal(ele.length, 0);
    await driver.quit();
  });
});

Full page screenshots

The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    driver.save_full_page_screenshot("full_page_screenshot.png")
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Context

The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");
Show full example
package dev.selenium.browsers;

import dev.selenium.BaseTest;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.service.DriverFinder;





public class FirefoxTest extends BaseTest {
  private FirefoxDriver driver;

  @AfterEach
  public void clearProperties() {
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);
    System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();
  }

  @Test
  public void basicOptions() {
    FirefoxOptions options = new FirefoxOptions();
    driver = new FirefoxDriver(options);
  }

  @Test
  public void arguments() {
    FirefoxOptions options = new FirefoxOptions();

    options.addArguments("-headless");

    driver = new FirefoxDriver(options);
  }

  @Test
  @DisabledOnOs(OS.WINDOWS)
  public void setBrowserLocation() {
    FirefoxOptions options = new FirefoxOptions();

    options.setBinary(getFirefoxLocation());

    driver = new FirefoxDriver(options);
  }

  @Test
  public void logsToFile() throws IOException {
    File logLocation = getTempFile("logsToFile", ".log");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogFile(logLocation).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsToConsole() throws IOException {
    File logLocation = getTempFile("logsToConsole", ".log");
    System.setOut(new PrintStream(logLocation));

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogOutput(System.out).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("geckodriver	INFO	Listening on"));
  }

  @Test
  public void logsWithLevel() throws IOException {
    File logLocation = getTempFile("logsWithLevel", ".log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
  }

  @Test
  public void stopsTruncatingLogs() throws IOException {
    File logLocation = getTempFile("geckodriver-", "log");
    System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY, logLocation.getAbsolutePath());
    System.setProperty(
        GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY, FirefoxDriverLogLevel.DEBUG.toString());

    FirefoxDriverService service =
        new GeckoDriverService.Builder().withTruncatedLogs(false).build();

    driver = new FirefoxDriver(service);

    String fileContent = new String(Files.readAllBytes(logLocation.toPath()));
    Assertions.assertFalse(fileContent.contains(" ... "));
  }

  @Test
  public void setProfileLocation() {
    File profileDirectory = getTempDirectory("profile-");
    FirefoxDriverService service =
        new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();

    driver = new FirefoxDriver(service);

    String location = (String) driver.getCapabilities().getCapability("moz:profile");
    Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));
  }


  @Test
  public void installAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");

    driver.installExtension(xpiPath);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }


  @Test
  public void uninstallAddon() {
    driver = startFirefoxDriver();
    Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
    String id = driver.installExtension(xpiPath);

    driver.uninstallExtension(id);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
  }


  @Test
  public void installUnsignedAddonPath() {
    driver = startFirefoxDriver();
    Path path = Paths.get("src/test/resources/extensions/selenium-example");

    driver.installExtension(path, true);

    driver.get("https://www.selenium.dev/selenium/web/blank.html");
    WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
    Assertions.assertEquals(
        "Content injected by webextensions-selenium-example", injected.getText());
  }

  private Path getFirefoxLocation() {
    FirefoxOptions options = new FirefoxOptions();
    options.setBrowserVersion("stable");
    DriverFinder finder = new DriverFinder(GeckoDriverService.createDefaultService(), options);
    return Path.of(finder.getBrowserPath());
  }

  @Test
  public void fullPageScreenshot() throws Exception {
    driver = startFirefoxDriver();

    driver.get("https://www.selenium.dev");

    File screenshot = driver.getFullPageScreenshotAs(OutputType.FILE);

    File targetFile = new File("full_page_screenshot.png");
    Files.move(screenshot.toPath(), targetFile.toPath());

    // Verify the screenshot file exists
    Assertions.assertTrue(targetFile.exists(), "The full page screenshot file should exist");
    Files.deleteIfExists(targetFile.toPath());

    driver.quit();
  }

  @Test
  public void setContext() {
    driver = startFirefoxDriver();

    ((HasContext) driver).setContext(FirefoxCommandContext.CHROME);
    driver.executeScript("console.log('Inside Chrome context');");

    // Verify the context is back to "content"
    Assertions.assertEquals(
            FirefoxCommandContext.CHROME, ((HasContext) driver).getContext(),
            "The context should be 'chrome'"
    );

    driver.quit();
  }

  @Test
  public void firefoxProfile() {
    FirefoxProfile profile = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();
    profile.setPreference("javascript.enabled", "False");
    options.setProfile(profile);

    driver = new FirefoxDriver(options);

    driver.quit();
  }
}
    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


def test_basic_options():
    options = webdriver.FirefoxOptions()
    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_arguments():
    options = webdriver.FirefoxOptions()

    options.add_argument("-headless")

    driver = webdriver.Firefox(options=options)
    driver.quit()


def test_set_browser_location(firefox_bin):
    options = webdriver.FirefoxOptions()

    options.binary_location = firefox_bin

    driver = webdriver.Firefox(options=options)

    driver.quit()


def test_log_to_file(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)
    driver.get("https://www.selenium.dev")

    with open(log_path, 'r') as fp:
        assert "geckodriver	INFO	Listening on" in fp.readline()

    driver.quit()


def test_log_to_stdout(capfd):
    service = webdriver.FirefoxService(log_output=subprocess.STDOUT)

    driver = webdriver.Firefox(service=service)

    out, err = capfd.readouterr()
    assert "geckodriver	INFO	Listening on" in out

    driver.quit()


def test_log_level(log_path):
    service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert '\tDEBUG' in f.read()

    driver.quit()


def test_log_truncation(log_path):
    service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)

    driver = webdriver.Firefox(service=service)

    with open(log_path, 'r') as f:
        assert ' ... ' not in f.read()

    driver.quit()


def test_profile_location(temp_dir):
    service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])

    driver = webdriver.Firefox(service=service)
    profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]

    assert profile_name in os.listdir(temp_dir)

    driver.quit()


def test_install_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    driver.install_addon(addon_path_xpi)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_uninstall_addon(firefox_driver, addon_path_xpi):
    driver = firefox_driver

    id = driver.install_addon(addon_path_xpi)
    driver.uninstall_addon(id)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0


def test_install_unsigned_addon_directory(firefox_driver, addon_path_dir):
    driver = firefox_driver

    driver.install_addon(addon_path_dir, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_install_unsigned_addon_directory_slash(firefox_driver, addon_path_dir_slash):
    driver = firefox_driver

    driver.install_addon(addon_path_dir_slash, temporary=True)

    driver.get("https://www.selenium.dev/selenium/web/blank.html")
    injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")

    assert injected.text == "Content injected by webextensions-selenium-example"


def test_full_page_screenshot(firefox_driver):
    driver = firefox_driver

    driver.get("https://www.selenium.dev")

    driver.save_full_page_screenshot("full_page_screenshot.png")

    assert os.path.exists("full_page_screenshot.png")

    driver.quit()


def test_set_context(firefox_driver):
    driver = firefox_driver

    with driver.context(driver.CONTEXT_CHROME):
        driver.execute_script("console.log('Inside Chrome context');")

    # Check if the context is back to content
    assert driver.execute("GET_CONTEXT")["value"] == "content"


def test_firefox_profile():
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

    options = Options()
    firefox_profile = FirefoxProfile()
    firefox_profile.set_preference("javascript.enabled", False)
    options.profile = firefox_profile

    driver = webdriver.Firefox(options=options)

    driver.quit()
      driver.context = 'content'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Firefox' do
  describe 'Options' do
    let(:firefox_location) { driver_finder && ENV.fetch('FIREFOX_BIN', nil) }

    it 'basic options' do
      options = Selenium::WebDriver::Options.firefox
      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'add arguments' do
      options = Selenium::WebDriver::Options.firefox

      options.args << '-headless'

      @driver = Selenium::WebDriver.for :firefox, options: options
    end

    it 'sets location of binary' do
      options = Selenium::WebDriver::Options.firefox

      options.binary = firefox_location

      @driver = Selenium::WebDriver.for :firefox, options: options
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('geckodriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.rm_rf(root_directory)
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.firefox

      service.log = file_name

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.firefox

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :firefox, service: service
      }.to output(/geckodriver	INFO	Listening on/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.firefox
      service.log = file_name

      service.args += %w[--log debug]

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/Marionette	DEBUG/).any?).to eq true
    end

    it 'stops truncating log lines' do
      service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])

      service.args << '--log-no-truncate'

      @driver = Selenium::WebDriver.for :firefox, service: service
      expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
    end

    it 'sets default profile location' do
      service = Selenium::WebDriver::Service.firefox

      service.args += ['--profile-root', root_directory]

      @driver = Selenium::WebDriver.for :firefox, service: service
      profile_location = Dir.new(@driver.capabilities['moz:profile'])
      expect(profile_location.path.gsub('\\', '/')).to include(root_directory)
    end
  end

  describe 'Features' do
    let(:driver) { start_firefox }

    it 'installs addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)

      driver.install_addon(extension_file_path)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'uninstalls addon' do
      extension_file_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example.xpi', __dir__)
      extension_id = driver.install_addon(extension_file_path)

      driver.uninstall_addon(extension_id)

      driver.get 'https://www.selenium.dev/selenium/web/blank.html'
      expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
    end

    it 'installs unsigned addon' do
      extension_dir_path = File.expand_path('../spec_support/extensions/webextensions-selenium-example/', __dir__)

      driver.install_addon(extension_dir_path, true)

      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      injected = driver.find_element(id: 'webextensions-selenium-example')
      expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
    end

    it 'takes full page screenshot' do
      driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
      Dir.mktmpdir('screenshot_test') do |dir|
        screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))

        expect(screenshot).to be_a File
      end
    end

    it 'sets the context' do
      driver.context = 'content'
      expect(driver.context).to eq 'content'
    end
  end

  describe 'Profile' do
    it 'creates a new profile' do
      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.dir'] = '/tmp/webdriver-downloads'
      options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
      expect(options.profile).to eq(profile)
    end
  end

  def driver_finder
    options = Selenium::WebDriver::Options.firefox(browser_version: 'stable')
    service = Selenium::WebDriver::Service.firefox
    finder = Selenium::WebDriver::DriverFinder.new(options, service)
    ENV['GECKODRIVER_BIN'] = finder.driver_path
    ENV['FIREFOX_BIN'] = finder.browser_path
  end
end

Note: As of Firefox 138, geckodriver needs to be started with the argument --allow-system-access to switch the context to CHROME.

4 - IE 特定功能

这些是 Microsoft Internet Explorer 浏览器特有的功能和特性.

自2022年6月起, Selenium 正式不再支持独立的 Internet Explorer. Internet Explorer 驱动程序仍支持在 “IE 兼容模式” 下运行 Microsoft Edge.

特别注意事项

IE 驱动程序是 Selenium 项目直接维护的唯一驱动程序. 虽然 32 位和 64 位版本的版本的二进制文件, 但有一些64位驱动程序的 已知限制. 因此, 建议使用 32 位驱动程序.

有关使用 Internet Explorer 的其他信息, 请参见 IE 驱动程序服务器页面

选项

在 Internet Explorer 兼容模式下启动 Microsoft Edge 浏览器, 并使用基本定义的选项, 看起来就像这样:

        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
            var options = new InternetExplorerOptions();
            options.AttachToEdgeChrome = true;
            options.EdgeExecutablePath = GetEdgeLocation();
            _driver = new InternetExplorerDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;

namespace SeleniumDocs.Browsers
{
    [TestClassCustom]
    [EnabledOnOs("WINDOWS")]
    public class InternetExplorerTest
    {
        private InternetExplorerDriver _driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            _driver.Quit();
        }

        [TestMethod]
        public void BasicOptionsWin10()
        {
            var options = new InternetExplorerOptions();
            options.AttachToEdgeChrome = true;
            options.EdgeExecutablePath = GetEdgeLocation();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        public void BasicOptionsWin11()
        {
            var options = new InternetExplorerOptions();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Console.WriteLine("Lines: {0}", lines);
            Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = InternetExplorerDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        public void LogsLevel()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
        }

        [TestMethod]
        public void SupportingFilesLocation()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();

            service.LibraryExtractionPath = GetTempDirectory();

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath == null || !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private string GetEdgeLocation()
        {
            return Environment.GetEnvironmentVariable("EDGE_BIN");
        }
    }
}
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end

截至 Internet Explorer 驱动程序 v4.5.0:

  • 如果系统中没有 IE(Windows 11 中的默认设置), 则无需使用上述两个参数. 使用上述两个参数.IE 驱动程序将使用 Edge, 并自动对其进行定位.
  • 如果系统上同时存在 IE 和 Edge, 则只需设置附加到 Edge、 IE 驱动程序将自动在系统中定位 Edge.

因此, 如果系统中没有 IE, 您只需要:

        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
            var options = new InternetExplorerOptions();
            _driver = new InternetExplorerDriver(options);
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;

namespace SeleniumDocs.Browsers
{
    [TestClassCustom]
    [EnabledOnOs("WINDOWS")]
    public class InternetExplorerTest
    {
        private InternetExplorerDriver _driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            _driver.Quit();
        }

        [TestMethod]
        public void BasicOptionsWin10()
        {
            var options = new InternetExplorerOptions();
            options.AttachToEdgeChrome = true;
            options.EdgeExecutablePath = GetEdgeLocation();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        public void BasicOptionsWin11()
        {
            var options = new InternetExplorerOptions();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Console.WriteLine("Lines: {0}", lines);
            Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = InternetExplorerDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        public void LogsLevel()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
        }

        [TestMethod]
        public void SupportingFilesLocation()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();

            service.LibraryExtractionPath = GetTempDirectory();

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath == null || !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private string GetEdgeLocation()
        {
            return Environment.GetEnvironmentVariable("EDGE_BIN");
        }
    }
}
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
<p><a href=/documentation/about/contributing/#moving-examples>
<span class="selenium-badge-code" data-bs-toggle="tooltip" data-bs-placement="right"
      title="One or more of these examples need to be implemented in the examples directory; click for details in the contribution guide">Move Code</span></a></p>


val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)

以下是几种具有不同功能的常见用例:

fileUploadDialogTimeout

在某些环境中, 当打开文件上传对话框时, Internet Explorer可能会超时. IEDriver的默认超时为1000毫秒, 但您可以使用fileUploadDialogTimeout功能来增加超时时间.

InternetExplorerOptions options = new InternetExplorerOptions();
options.waitForUploadDialogUpTo(Duration.ofSeconds(2));
WebDriver driver = new RemoteWebDriver(options); 
  
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
  
      @options.file_upload_dialog_timeout = 2000
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
          .setIeOptions(options)
          .build();  
  
val options = InternetExplorerOptions()
options.waitForUploadDialogUpTo(Duration.ofSeconds(2))
val driver = RemoteWebDriver(options)
  

ensureCleanSession

设置为 true时, 此功能将清除InternetExplorer所有正在运行实例的 缓存, 浏览器历史记录和Cookies (包括手动启动或由驱动程序启动的实例) . 默认情况下, 此设置为 false.

使用此功能将导致启动浏览器时性能下降, 因为驱动程序将等待直到缓存清除后再启动IE浏览器.

此功能接受一个布尔值作为参数.

InternetExplorerOptions options = new InternetExplorerOptions();
options.destructivelyEnsureCleanSession();
WebDriver driver = new RemoteWebDriver(options);
  
    options = webdriver.IeOptions()
    options.ensure_clean_session = True
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
var options = new InternetExplorerOptions();
options.EnsureCleanSession = true;
var driver = new RemoteWebDriver(options);
  
      @options.ensure_clean_session = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ensureCleanSession(true);
let driver = await Builder()
          .setIeOptions(options)
          .build(); 
  
val options = InternetExplorerOptions()
options.destructivelyEnsureCleanSession()
val driver = RemoteWebDriver(options)
  

ignoreZoomSetting

InternetExplorer驱动程序期望浏览器的缩放级别为100%, 否则驱动程序将可能抛出异常. 通过将 ignoreZoomSetting 设置为 true, 可以禁用此默认行为.

此功能接受一个布尔值作为参数.

InternetExplorerOptions options = new InternetExplorerOptions();
options.ignoreZoomSettings();
WebDriver driver = new RemoteWebDriver(options);
  
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
var options = new InternetExplorerOptions();
options.IgnoreZoomLevel = true;
var driver = new RemoteWebDriver(options);
  
      @options.ignore_zoom_level = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ignoreZoomSetting(true);
let driver = await Builder()
          .setIeOptions(options)
          .build(); 
  
val options = InternetExplorerOptions()
options.ignoreZoomSettings()
val driver = RemoteWebDriver(options)
  

ignoreProtectedModeSettings

启动新的IE会话时是否跳过 保护模式 检查.

如果未设置, 并且所有区域的 保护模式 设置都不同, 则驱动程序将可能引发异常.

如果将功能设置为 true, 则测试可能会变得不稳定, 无响应, 或者浏览器可能会挂起. 但是, 到目前为止, 这仍然是第二好的选择, 并且第一选择应该 始终 是手动实际设置每个区域的保护模式设置. 如果用户正在使用此属性, 则只会给予 “尽力而为” 的支持.

此功能接受一个布尔值作为参数.

InternetExplorerOptions options = new InternetExplorerOptions();
options.introduceFlakinessByIgnoringSecurityDomains();
WebDriver driver = new RemoteWebDriver(options);
  
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new RemoteWebDriver(options);
  
      @options.ignore_protected_mode_settings = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().introduceFlakinessByIgnoringProtectedModeSettings(true);
let driver = await Builder()
          .setIeOptions(options)
          .build(); 
  
val options = InternetExplorerOptions()
options.introduceFlakinessByIgnoringSecurityDomains()
val driver = RemoteWebDriver(options)
  

silent

设置为 true时, 此功能将禁止IEDriverServer的诊断输出.

此功能接受一个布尔值作为参数.

InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("silent", true);
WebDriver driver = new InternetExplorerDriver(options);
  
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalInternetExplorerOption("silent", true);
IWebDriver driver = new InternetExplorerDriver(options);
  
      @options.silent = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const {Builder,By, Capabilities} = require('selenium-webdriver');
let caps = Capabilities.ie();
caps.set('silent', true);

(async function example() {
    let driver = await new Builder()
        .forBrowser('internet explorer')
        .withCapabilities(caps)
        .build();
    try {
        await driver.get('http://www.google.com/ncr');
    }
    finally {
        await driver.quit();
    }
})();
  
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions

fun main() {
    val options = InternetExplorerOptions()
    options.setCapability("silent", true)
    val driver = InternetExplorerDriver(options)
    try {
        driver.get("https://google.com/ncr")
        val caps = driver.getCapabilities()
        println(caps)
    } finally {
        driver.quit()
    }
}
  

IE 命令行选项

Internet Explorer包含几个命令行选项, 使您可以进行故障排除和配置浏览器.

下面介绍了一些受支持的命令行选项

  • -private : 用于在私有浏览模式下启动IE. 这适用于IE 8和更高版本.

  • -k : 在kiosk模式下启动Internet Explorer. 浏览器在一个最大化的窗口中打开, 该窗口不显示地址栏, 导航按钮或状态栏.

  • -extoff : 在无附加模式下启动IE. 此选项专门用于解决浏览器加载项问题. 在IE 7和更高版本中均可使用.

注意: forceCreateProcessApi 应该启用命令行参数才能正常工作.

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;

public class ieTest {
    public static void main(String[] args) {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.useCreateProcessApiToLaunchIe();
        options.addCommandSwitches("-k");
        InternetExplorerDriver driver = new InternetExplorerDriver(options);
        try {
            driver.get("https://google.com/ncr");
            Capabilities caps = driver.getCapabilities();
            System.out.println(caps);
        } finally {
            driver.quit();
        }
    }
}
  
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace ieTest {
 class Program {
  static void Main(string[] args) {
   InternetExplorerOptions options = new InternetExplorerOptions();
   options.ForceCreateProcessApi = true;
   options.BrowserCommandLineArguments = "-k";
   IWebDriver driver = new InternetExplorerDriver(options);
   driver.Url = "https://google.com/ncr";
  }
 }
}
  
      @options.add_argument('-k')
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.addBrowserCommandSwitches('-k');
options.addBrowserCommandSwitches('-private');
options.forceCreateProcessApi(true);

driver = await env.builder()
          .setIeOptions(options)
          .build();
  
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions

fun main() {
    val options = InternetExplorerOptions()
    options.useCreateProcessApiToLaunchIe()
    options.addCommandSwitches("-k")
    val driver = InternetExplorerDriver(options)
    try {
        driver.get("https://google.com/ncr")
        val caps = driver.getCapabilities()
        println(caps)
    } finally {
        driver.quit()
    }
}
  

forceCreateProcessApi

强制使用CreateProcess API启动Internet Explorer. 默认值为false.

对于IE 8及更高版本, 此选项要求将 “TabProcGrowth” 注册表值设置为0.

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;

public class ieTest {
    public static void main(String[] args) {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.useCreateProcessApiToLaunchIe();
        InternetExplorerDriver driver = new InternetExplorerDriver(options);
        try {
            driver.get("https://google.com/ncr");
            Capabilities caps = driver.getCapabilities();
            System.out.println(caps);
        } finally {
            driver.quit();
        }
    }
}
  
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace ieTest {
 class Program {
  static void Main(string[] args) {
   InternetExplorerOptions options = new InternetExplorerOptions();
   options.ForceCreateProcessApi = true;
   IWebDriver driver = new InternetExplorerDriver(options);
   driver.Url = "https://google.com/ncr";
  }
 }
}
  
      @options.force_create_process_api = true
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);

driver = await env.builder()
          .setIeOptions(options)
          .build();
  
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions

fun main() {
    val options = InternetExplorerOptions()
    options.useCreateProcessApiToLaunchIe()
    val driver = InternetExplorerDriver(options)
    try {
        driver.get("https://google.com/ncr")
        val caps = driver.getCapabilities()
        println(caps)
    } finally {
        driver.quit()
    }
}
  

服务

Service page 描述了所有浏览器通用的服务设置.

日志输出

获取驱动程序日志有助于调试各种问题. 服务类可让您指示日志的去向. 除非用户指定了日志输出的位置, 否则日志输出将被忽略.

文件输出

更改日志输出以保存到特定文件:

Selenium v4.10

                .withLogFile(getLogLocation())
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}

Note: Java also allows setting file output by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: String representing path to log file

    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()

Selenium v4.10

      service.log = file_name
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end

控制台输出

要更改日志输出, 使其在控制台中显示为标准输出:

Selenium v4.10

                .withLogOutput(System.out)
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}

Note: Java also allows setting console output by System Property;
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: DriverService.LOG_STDOUT or DriverService.LOG_STDERR

Selenium v4.11

    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()

Selenium v4.10

      service.log = $stdout
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end

日志级别

有 6 种可用的日志级别:FATALERRORWARNINFODEBUGTRACE 如果指定了日志输出, 默认级别为FATAL.

                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}

Note: Java also allows setting log level by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY
Property value: String representation of InternetExplorerDriverLogLevel.DEBUG.toString() enum

    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;

namespace SeleniumDocs.Browsers
{
    [TestClassCustom]
    [EnabledOnOs("WINDOWS")]
    public class InternetExplorerTest
    {
        private InternetExplorerDriver _driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            _driver.Quit();
        }

        [TestMethod]
        public void BasicOptionsWin10()
        {
            var options = new InternetExplorerOptions();
            options.AttachToEdgeChrome = true;
            options.EdgeExecutablePath = GetEdgeLocation();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        public void BasicOptionsWin11()
        {
            var options = new InternetExplorerOptions();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Console.WriteLine("Lines: {0}", lines);
            Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = InternetExplorerDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        public void LogsLevel()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
        }

        [TestMethod]
        public void SupportingFilesLocation()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();

            service.LibraryExtractionPath = GetTempDirectory();

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath == null || !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private string GetEdgeLocation()
        {
            return Environment.GetEnvironmentVariable("EDGE_BIN");
        }
    }
}

Selenium v4.10

      service.args << '-log-level=WARN'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end

辅助文件路径

                .withExtractPath(getTempDirectory())
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;

@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
    public InternetExplorerDriver driver;
    private File logLocation;
    private File tempDirectory;

    @AfterEach
    public void quit() {
        if (logLocation != null && logLocation.exists()) {
            logLocation.delete();
        }
        if (tempDirectory  != null && tempDirectory.exists()) {
            tempDirectory.delete();
        }

        driver.quit();
    }

    @Test
    public void basicOptionsWin10() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.attachToEdgeChrome();
        options.withEdgeExecutablePath(getEdgeLocation());
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void basicOptionsWin11() {
        InternetExplorerOptions options = new InternetExplorerOptions();
        driver = new InternetExplorerDriver(options);
    }

    @Test
    public void logsToFile() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogFile(getLogLocation())
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsToConsole() throws IOException {
        System.setOut(new PrintStream(getLogLocation()));

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogOutput(System.out)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
    }

    @Test
    public void logsWithLevel() throws IOException {
        System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
                getLogLocation().getAbsolutePath());

        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withLogLevel(InternetExplorerDriverLogLevel.WARN)
                .build();

        driver = new InternetExplorerDriver(service);

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
        Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
    }

    @Test
    public void supportingFilesLocation() throws IOException {
        InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
                .withExtractPath(getTempDirectory())
                .build();

        driver = new InternetExplorerDriver(service);
        Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
    }

    private File getLogLocation() throws IOException {
        if (logLocation == null || !logLocation.exists()) {
            logLocation = File.createTempFile("iedriver-", ".log");
        }

        return logLocation;
    }

    private File getTempDirectory() throws IOException {
        if (tempDirectory == null || !tempDirectory.exists()) {
            tempDirectory = Files.createTempDirectory("supporting-").toFile();
        }

        return tempDirectory;
    }

    private String getEdgeLocation() {
        return System.getenv("EDGE_BIN");
    }
}
**Note**: Java also allows setting log level by System Property:\ Property key: `InternetExplorerDriverService.IE_DRIVER_EXTRACT_PATH_PROPERTY`\ Property value: String representing path to supporting files directory

Selenium v4.11

    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)
Show full example
import os
import subprocess
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10(edge_bin):
    options = webdriver.IeOptions()
    options.attach_to_edge_chrome = True
    options.edge_executable_path = edge_bin
    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
    options = webdriver.IeOptions()
    driver = webdriver.Ie(options=options)

    driver.quit()

@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_file_upload_timeout():
    options = webdriver.IeOptions()
    options.file_upload_timeout = 2000

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ensure_clean_session():
    options = webdriver.IeOptions()
    options.ensure_clean_session = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_zoom_level():
    options = webdriver.IeOptions()
    options.ignore_zoom_level = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_ignore_protected_mode_settings():
    options = webdriver.IeOptions()
    options.ignore_protected_mode_settings = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_silent():
    service = webdriver.IeService(service_args=["--silent"])
    driver = webdriver.Ie(service=service)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_cmd_options():
    options = webdriver.IeOptions()
    options.add_argument("-private")

    driver = webdriver.Ie(options=options)

    driver.quit()

# Skipping this as it fails on Windows because the value of registry setting in 
# HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' 
@pytest.mark.skip
def test_force_create_process_api():
    options = webdriver.IeOptions()
    options.force_create_process_api = True

    driver = webdriver.Ie(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="INFO")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Starting WebDriver server" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_stdout(capfd):
    service = webdriver.IeService(log_output=subprocess.STDOUT)

    driver = webdriver.Ie(service=service)

    out, err = capfd.readouterr()
    assert "Started InternetExplorerDriver server" in out

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
    service = webdriver.IeService(log_output=log_path, log_level="WARN")

    driver = webdriver.Ie(service=service)

    with open(log_path, "r") as fp:
        assert "Started InternetExplorerDriver server (32-bit)" in fp.readline()

    driver.quit()


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
    service = webdriver.IeService(service_args=["–extract-path=" + temp_dir])

    driver = webdriver.Ie(service=service)

    driver.quit()
Show full example
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;

namespace SeleniumDocs.Browsers
{
    [TestClassCustom]
    [EnabledOnOs("WINDOWS")]
    public class InternetExplorerTest
    {
        private InternetExplorerDriver _driver;
        private string _logLocation;
        private string _tempPath;

        [TestCleanup]
        public void Cleanup()
        {
            if (_logLocation != null && File.Exists(_logLocation))
            {
                File.Delete(_logLocation);
            }
            if (_tempPath != null && File.Exists(_tempPath))
            {
                File.Delete(_tempPath);
            }
            _driver.Quit();
        }

        [TestMethod]
        public void BasicOptionsWin10()
        {
            var options = new InternetExplorerOptions();
            options.AttachToEdgeChrome = true;
            options.EdgeExecutablePath = GetEdgeLocation();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        public void BasicOptionsWin11()
        {
            var options = new InternetExplorerOptions();
            _driver = new InternetExplorerDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToFile()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Console.WriteLine("Lines: {0}", lines);
            Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void LogsToConsole()
        {
            var stringWriter = new StringWriter();
            var originalOutput = Console.Out;
            Console.SetOut(stringWriter);

            var service = InternetExplorerDriverService.CreateDefaultService();

            //service.LogToConsole = true;

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(stringWriter.ToString().Contains("geckodriver	INFO	Listening on"));
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }

        [TestMethod]
        public void LogsLevel()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();
            service.LogFile = GetLogLocation();

            service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;

            _driver = new InternetExplorerDriver(service);
            _driver.Quit(); // Close the Service log file before reading
            var lines = File.ReadLines(GetLogLocation());
            Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
        }

        [TestMethod]
        public void SupportingFilesLocation()
        {
            var service = InternetExplorerDriverService.CreateDefaultService();

            service.LibraryExtractionPath = GetTempDirectory();

            _driver = new InternetExplorerDriver(service);
            Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
        }

        private string GetLogLocation()
        {
            if (_logLocation == null || !File.Exists(_logLocation))
            {
                _logLocation = Path.GetTempFileName();
            }

            return _logLocation;
        }

        private string GetTempDirectory()
        {
            if (_tempPath == null || !File.Exists(_tempPath))
            {
                _tempPath = Path.GetTempPath();
            }

            return _tempPath;
        }

        private string GetEdgeLocation()
        {
            return Environment.GetEnvironmentVariable("EDGE_BIN");
        }
    }
}

Selenium v4.8

      service.args << "–extract-path=#{root_directory}"
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
  describe 'Options' do
    let(:edge_location) { ENV.fetch('EDGE_BIN', nil) }
    let(:url) { 'https://www.selenium.dev/selenium/web/' }

    before do
      @options = Selenium::WebDriver::IE::Options.new
      @options.attach_to_edge_chrome = true
      @options.edge_executable_path = edge_location
    end

    it 'basic options Win10' do
      options = Selenium::WebDriver::IE::Options.new
      options.attach_to_edge_chrome = true
      options.edge_executable_path = edge_location
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'basic options Win11' do
      options = Selenium::WebDriver::Options.ie
      @driver = Selenium::WebDriver.for :ie, options: options
    end

    it 'sets the file upload dialog timeout' do
      @options.file_upload_dialog_timeout = 2000
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ensures a clean session' do
      @options.ensure_clean_session = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the zoom setting' do
      @options.ignore_zoom_level = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'ignores the protected mode settings' do
      @options.ignore_protected_mode_settings = true
      driver = Selenium::WebDriver.for(:ie, options: @options)
      driver.quit
    end

    it 'adds the silent option', skip: 'This capability will be added on the release 4.22.0' do
      @options.silent = true
      expect(@options.silent).to be_truthy
    end

    it 'sets the command line options' do
      @options.add_argument('-k')
      Selenium::WebDriver.for(:ie, options: @options)
    end

    it 'launches ie with the create process api', skip: 'When using with IE 8 or higher, it needs a registry value' do
      @options.force_create_process_api = true
      Selenium::WebDriver.for(:ie, options: @options)
      expect(@options.instance_variable_get(:@options)['force_create_process_api'])
        .to eq({force_create_process_api: true})
    end
  end

  describe 'Service' do
    let(:file_name) { Tempfile.new('iedriver').path }
    let(:root_directory) { Dir.mktmpdir }

    after do
      FileUtils.rm_f(file_name)
      FileUtils.remove_entry root_directory
    end

    it 'logs to file' do
      service = Selenium::WebDriver::Service.ie

      service.log = file_name

      @driver = Selenium::WebDriver.for :ie, service: service
      expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
    end

    it 'logs to console' do
      service = Selenium::WebDriver::Service.ie

      service.log = $stdout

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
    end

    it 'sets log level' do
      service = Selenium::WebDriver::Service.ie
      service.log = $stdout

      service.args << '-log-level=WARN'

      expect {
        @driver = Selenium::WebDriver.for :ie, service: service
      }.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
    end

    it 'sets location for supporting files' do
      service = Selenium::WebDriver::Service.ie

      service.args << "–extract-path=#{root_directory}"

      @driver = Selenium::WebDriver.for :ie, service: service
    end
  end
end

5 - Safari 特定功能

这些是特定于Apple Safari浏览器的功能和特性.

与Chromium和Firefox驱动不同, safari驱动随操作系统安装. 要在 Safari 上启用自动化, 请从终端运行以下命令:

safaridriver --enable

选项

所有浏览器通用的Capabilities在选项页.

Safari独有的Capabilities可以在Apple的页面关于Safari的WebDriver 上找到

使用基本定义的选项启动 Safari 会话如下所示:

        SafariOptions options = new SafariOptions();
        driver = new SafariDriver(options);
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;

@EnabledOnOs(OS.MAC)
public class SafariTest {
    public SafariDriver driver;

    @AfterEach
    public void quit() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void basicOptions() {
        SafariOptions options = new SafariOptions();
        driver = new SafariDriver(options);
    }

    @Test
    public void enableLogs() {
        SafariDriverService service = new SafariDriverService.Builder()
                .withLogging(true)
                .build();

        driver = new SafariDriver(service);
    }
    
    public void safariTechnologyPreview() {
        SafariOptions options = new SafariOptions();
        options.setUseTechnologyPreview(true);
        driver = new SafariDriver(options);
    }
}
    options = webdriver.SafariOptions()
    driver = webdriver.Safari(options=options)
Show full example
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
    options = webdriver.SafariOptions()
    driver = webdriver.Safari(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
    service = webdriver.SafariService(enable_logging=True)

    driver = webdriver.Safari(service=service)

    driver.quit()

@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
    options = webdriver.SafariOptions()
    options.use_technology_preview = True
    service = webdriver.SafariService(
        executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
    )
    driver = webdriver.Safari(options=options, service=service)

    driver.quit()

            var options = new SafariOptions();
            driver = new SafariDriver(options);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Safari;
using SeleniumDocs.TestSupport;

namespace SeleniumDocs.Browsers
{
    [TestClassCustom]
    [EnabledOnOs("OSX")]
    public class SafariTest
    {
        private SafariDriver driver;

        [TestCleanup]
        public void QuitDriver()
        {
            driver.Quit();
        }

        [TestMethod]
        public void BasicOptions()
        {
            var options = new SafariOptions();
            driver = new SafariDriver(options);
        }

        [TestMethod]
        [Ignore("Not implemented")]
        public void EnableLogs()
        {
            var service = SafariDriverService.CreateDefaultService();

            //service.EnableLogging = true;

            driver = new SafariDriver(service);
        }
    }
}
      options = Selenium::WebDriver::Options.safari
      @driver = Selenium::WebDriver.for :safari, options: options
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Safari', exclusive: {platform: :macosx} do
  describe 'Options' do
    it 'basic options' do
      options = Selenium::WebDriver::Options.safari
      @driver = Selenium::WebDriver.for :safari, options: options
    end
  end

  describe 'Service' do
    let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }

    it 'enables logs' do
      original_count = Dir[directory].length
      service = Selenium::WebDriver::Service.safari

      service.args << '--diagnose'

      @driver = Selenium::WebDriver.for :safari, service: service
      expect(Dir[directory].length - original_count).to eq 1
    end

    it 'does not set log output' do
      service = Selenium::WebDriver::Service.safari

      expect {
        service.log = $stdout
      }.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
    end
  end
end

RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
  it 'sets the technology preview' do
    Selenium::WebDriver::Safari.technology_preview!
    local_driver = Selenium::WebDriver.for :safari
    expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
  end
end
    let driver = new Builder()
      .forBrowser(Browser.SAFARI)
      .setSafariOptions(options)
      .build();
Show full example
const safari = require('selenium-webdriver/safari');
const {Browser, Builder} = require("selenium-webdriver");
const options = new safari.Options();
const process  =  require('node:process');

describe('Should be able to Test Command line arguments', function () {
  (process.platform === 'darwin' ? it : it.skip)('headless', async function () {
    let driver = new Builder()
      .forBrowser(Browser.SAFARI)
      .setSafariOptions(options)
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
  });
});
val options = SafariOptions()
val driver = SafariDriver(options)

移动端

那些希望在iOS上自动化Safari的人可以参考 Appium 项目.

服务

所有浏览器通用的服务设置在 服务页面.

日志

与其他浏览器不同, Safari 浏览器不允许您选择日志的输出位置或更改级别. 一个可用选项是关闭或打开日志. 如果日志处于打开状态, 则可以在以下位置找到它们: ~/Library/Logs/com.apple.WebDriver/.

Selenium v4.10

                .withLogging(true)
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;

@EnabledOnOs(OS.MAC)
public class SafariTest {
    public SafariDriver driver;

    @AfterEach
    public void quit() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void basicOptions() {
        SafariOptions options = new SafariOptions();
        driver = new SafariDriver(options);
    }

    @Test
    public void enableLogs() {
        SafariDriverService service = new SafariDriverService.Builder()
                .withLogging(true)
                .build();

        driver = new SafariDriver(service);
    }
    
    public void safariTechnologyPreview() {
        SafariOptions options = new SafariOptions();
        options.setUseTechnologyPreview(true);
        driver = new SafariDriver(options);
    }
}

注意: Java也允许使用环境变量进行设置;
属性键: SafariDriverService.SAFARI_DRIVER_LOGGING
属性值: "true""false"

Selenium v4.26

    service = webdriver.SafariService(enable_logging=True)
Show full example
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
    options = webdriver.SafariOptions()
    driver = webdriver.Safari(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
    service = webdriver.SafariService(enable_logging=True)

    driver = webdriver.Safari(service=service)

    driver.quit()

@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
    options = webdriver.SafariOptions()
    options.use_technology_preview = True
    service = webdriver.SafariService(
        executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
    )
    driver = webdriver.Safari(options=options, service=service)

    driver.quit()

Selenium v4.8

      service.args << '--diagnose'
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Safari', exclusive: {platform: :macosx} do
  describe 'Options' do
    it 'basic options' do
      options = Selenium::WebDriver::Options.safari
      @driver = Selenium::WebDriver.for :safari, options: options
    end
  end

  describe 'Service' do
    let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }

    it 'enables logs' do
      original_count = Dir[directory].length
      service = Selenium::WebDriver::Service.safari

      service.args << '--diagnose'

      @driver = Selenium::WebDriver.for :safari, service: service
      expect(Dir[directory].length - original_count).to eq 1
    end

    it 'does not set log output' do
      service = Selenium::WebDriver::Service.safari

      expect {
        service.log = $stdout
      }.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
    end
  end
end

RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
  it 'sets the technology preview' do
    Selenium::WebDriver::Safari.technology_preview!
    local_driver = Selenium::WebDriver.for :safari
    expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
  end
end

Safari Technology Preview

Apple 提供了其浏览器的开发版本 — Safari Technology Preview

在代码中使用此版本:

        options.setUseTechnologyPreview(true);
        driver = new SafariDriver(options);
Show full example
package dev.selenium.browsers;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;

@EnabledOnOs(OS.MAC)
public class SafariTest {
    public SafariDriver driver;

    @AfterEach
    public void quit() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void basicOptions() {
        SafariOptions options = new SafariOptions();
        driver = new SafariDriver(options);
    }

    @Test
    public void enableLogs() {
        SafariDriverService service = new SafariDriverService.Builder()
                .withLogging(true)
                .build();

        driver = new SafariDriver(service);
    }
    
    public void safariTechnologyPreview() {
        SafariOptions options = new SafariOptions();
        options.setUseTechnologyPreview(true);
        driver = new SafariDriver(options);
    }
}
    options = webdriver.SafariOptions()
    options.use_technology_preview = True
    service = webdriver.SafariService(
        executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
    )
    driver = webdriver.Safari(options=options, service=service)
Show full example
import sys

import pytest
from selenium import webdriver


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
    options = webdriver.SafariOptions()
    driver = webdriver.Safari(options=options)

    driver.quit()


@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
    service = webdriver.SafariService(enable_logging=True)

    driver = webdriver.Safari(service=service)

    driver.quit()

@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
    options = webdriver.SafariOptions()
    options.use_technology_preview = True
    service = webdriver.SafariService(
        executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
    )
    driver = webdriver.Safari(options=options, service=service)

    driver.quit()

    Selenium::WebDriver::Safari.technology_preview!
    local_driver = Selenium::WebDriver.for :safari
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Safari', exclusive: {platform: :macosx} do
  describe 'Options' do
    it 'basic options' do
      options = Selenium::WebDriver::Options.safari
      @driver = Selenium::WebDriver.for :safari, options: options
    end
  end

  describe 'Service' do
    let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }

    it 'enables logs' do
      original_count = Dir[directory].length
      service = Selenium::WebDriver::Service.safari

      service.args << '--diagnose'

      @driver = Selenium::WebDriver.for :safari, service: service
      expect(Dir[directory].length - original_count).to eq 1
    end

    it 'does not set log output' do
      service = Selenium::WebDriver::Service.safari

      expect {
        service.log = $stdout
      }.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
    end
  end
end

RSpec.describe 'Safari Technology Preview', skip: "This test is being skipped as GitHub Actions have no support for Safari Technology Preview" do
  it 'sets the technology preview' do
    Selenium::WebDriver::Safari.technology_preview!
    local_driver = Selenium::WebDriver.for :safari
    expect(local_driver.capabilities.browser_name).to eq 'Safari Technology Preview'
  end
end