各ブラウザにはカスタム機能とユニークな特徴があります。
これは、このセクションの複数ページの印刷可能なビューです。 印刷するには、ここをクリックしてください.
対応ブラウザ
- 1: Chrome固有の機能
- 2: Edge固有の機能
- 3: Firefox特有の機能
- 4: IE特有の機能
- 5: Safari特有の機能
1 - Chrome固有の機能
これらは、Google Chromeブラウザに特有の機能と機能です。 デフォルトでは、Selenium 4はChrome v75以上と互換性があります。Chromeブラウザのバージョンとchromedriverのバージョンは、メジャーバージョンが一致する必要があることに注意してください。
Options
すべてのブラウザに共通する機能は オプション ページに記載されています。
ChromeおよびChromiumに特有の機能は、Googleの 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
パラメータは、ブラウザを起動する際に使用するコマンドラインスイッチのリストです。これらの引数を調査するための優れたリソースが2つあります:
一般的に使用されるargsには以下が含まれます:--start-maximized
, --headless=new
and --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ファイルを受け入れます
The 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に設定すると、ドライバープロセスが終了した後もブラウザを開いたままにできます。
注意: これはすでに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
注意: これはすでに.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 Source Codeから解析できます。
オプションに除外された引数を設定します。
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オブジェクトを作成するための例や、ドライバーの場所とポートを設定する方法は、Driver 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
プロパティ値: ログファイルへのパスを表す文字列
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();
}
}
}
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
コンソール出力
ログ出力をコンソールにSTDOUTとして表示するように変更するには:
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_STDOUT
または DriverService.LOG_STDERR
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
と $stderr
はどちらも有効な値です。
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
ログレベル
利用可能なログレベルは6つあります:ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, そして OFF
。--verbose
は --log-level=ALL
と同等であり、--silent
は --log-level=OFF
と同等であることに注意してください。このため、この例ではログレベルを一般的に設定しています:
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
列挙型の文字列表現
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
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つの機能があります:
- ログの追加
- 読みやすいタイムスタンプ
これらを使用するには、ログパスとログレベルも明示的に指定する必要があります。ログ出力はプロセスではなくドライバーによって管理されるため、若干の違いが見られる場合があります。
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
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でドライバーを強制的に使用できます。ただし、これはサポートされていない機能であり、バグは調査されません。
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"
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();
}
}
}
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
特別な機能
一部のブラウザは、それぞれに特有の追加機能を実装しています。
キャスティング
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
ネットワークの状態
さまざまなネットワークの状態をシミュレートできます。
以下の例はローカルWebDriver用です。リモートWebDriverについては、リモート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
デベロッパー ツール
Chromeデベロッパーツールの使用に関する詳細については、[Chromeデベロッパー ツール] セクションを参照してください。
2 - Edge固有の機能
Microsoft EdgeはChromiumで実装されており、サポートされている最も古いバージョンはv79です。 Chromeと同様に、edgedriverのメジャー バージョン番号は、Edgeブラウザのメジャーバージョンと一致する必要があります。
Chromeページ にあるすべての機能とオプションは、Edgeでも機能します。
オプション
すべてのブラウザに共通する機能はオプション ページに記載されています。
Chromiumに特有の機能は、GoogleのCapabilities & ChromeOptionsページに文書化されています。
基本的な定義済みオプションを使用して Edgeセッションを開始すると、次のようになります。
EdgeOptions options = getDefaultEdgeOptions();
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
パラメータは、ブラウザを起動する際に使用されるコマンドラインスイッチのリストです。これらの引数を調査するための優れたリソースが2つあります:
一般的に使用される引数には、--start-maximized
および --headless=new
が含まれます。 and --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.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.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.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 に設定すると、プロセスが終了した後でもブラウザが開いたままになります。ただし、quit コマンドがドライバーに送信されない限り、ブラウザは開いたままになります。
注意: これはすでに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
注意: これはすでに.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.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 Service ページにあります。
ログ出力
ドライバのログを取得することは、問題をデバッグするのに役立ちます。サービスクラスを使用すると、ログの出力先を指定できます。ユーザーがどこかにログを指示しない限り、ログ出力は無視されます。
ファイル出力
特定のファイルに保存するようにログ出力を変更するには、以下のようにします:
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でもシステムプロパティを使用してファイル出力を設定できます:
プロパティキー: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
プロパティ値: ログファイルのパスを表す文字列
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();
}
}
}
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
コンソール出力
ログ出力をコンソールにSTDOUTとして表示するには:
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_STDOUT
または DriverService.LOG_STDERR
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
と $stderr
はどちらも有効な値です。
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
と同等です。したがって、この例ではログレベルを一般的に設定しています:
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
プロパティ値:ChromiumDriverLogLevel
列挙型の文字列表現
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
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つの機能があります:
- ログの追加
- 読みやすいタイムスタンプ
これらを使用するには、ログパスとログレベルも明示的に指定する必要があります。ログ出力はプロセスではなくドライバによって管理されるため、若干の違いが見られることがあります。
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では、これらの機能をSystem Propertyによって切り替えることもできます:
プロパティキー: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
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でドライバを強制的に使用できます。 この機能はサポートされていないことに注意してください。バグは調査されません。
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();
}
}
}
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 Compatibility モード
Microsoft Edge は、Internet Explorer ドライバークラスを Microsoft Edgeと組み合わせて使用する “Internet Explorer 互換モード"で動かすことができます。 詳細については、Internet Explorerページを参照してください。
特別な機能
一部のブラウザは、それぞれ特有の追加機能を実装しています。
キャスティング
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
DevTools
EdgeでDevToolsを使用する際の詳細については、[Chrome DevTools]セクションを参照してください。
3 - Firefox特有の機能
Selenium 4 には Firefox 78 以降が必要です。 常に最新バージョンの geckodriver を使用することをお勧めします。
オプション
全ブラウザに共通のCapabilityについては、オプションページで説明しています。
Firefox に固有のCapabilityは、Mozilla のページの firefoxOptions にあります。
基本的な定義済みのオプションを使用して Firefox セッションを開始すると、以下のようになります。
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');
});
});
さまざまなCapabilityを備えた一般的な使用例をいくつか示します。
引数
args
パラメータは、ブラウザの起動時に使用するコマンドラインスイッチのリストです。
一般的に使用される引数には、 -headless
と "-profile"
、"/path/to/profile"
が含まれます。
オプションに引数を追加します。
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();
});
});
指定したロケーションでブラウザを起動する
binary
パラメーターは、使用するブラウザーの別のロケーションのパスを取ります。
たとえば、このパラメーターを使用すると、geckodriver を使用して、製品版とFirefox Nightlyの両方がコンピューターに存在する場合、
製品版の代わりに Firefox Nightly を駆動できます 。
オプションにブラウザーのロケーションを追加します。
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
プロファイル
Firefoxプロファイルを操作するにはいくつかの方法があります。
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 pageに記載されています。
ログ出力
ドライバーログを取得することは、さまざまな問題のデバッグに役立ちます。サービスクラスを使用すると、ログの保存先を指定できます。ログ出力は、ユーザーがどこかに指定しない限り無視されます。
ファイル出力
特定のファイルにログ出力を保存するには:
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();
}
}
注: Java では、システムプロパティによってファイル出力を設定することもできます。
プロパティキー:GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
プロパティ値: ログファイルへのパスを表す文字列
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()
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
コンソール出力
ログ出力をコンソールに表示するには、以下のようにします:
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();
}
}
注意: Javaは、システムプロパティを使用してコンソール出力を設定することもできます;
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
プロパティ値: DriverService.LOG_STDOUT
または DriverService.LOG_STDERR
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()
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
ログレベル
利用可能なログレベルは7つあります: fatal
, error
, warn
, info
, config
, debug
, trace
。
ロギングが指定されている場合、デフォルトのレベルは info
になります。
-v
iは -log debug
と同等であり、-vv
は log trace
と同等です。
したがって、この例は一般的にログレベルを設定するためのものです:
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();
}
}
注意: Javaは、システムプロパティによってログレベルの設定も可能です:
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
プロパティ値:FirefoxDriverLogLevel
列挙型の文字列表現
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()
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
トランケートログ
ドライバーは、大きなバイナリの文字列表現を含む、送信されたすべてのものをログに記録します。そのため、Firefoxではデフォルトで行が切り捨てられます。切り捨てを無効にするには:
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();
}
}
注意: Javaでは、システムプロパティによってログレベルを設定することもできます。
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
プロパティ値: "true"
または "false"
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()
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
プロファイルルート
プロファイルのデフォルトディレクトリは、システムの一時ディレクトリです。そのディレクトリにアクセスできない場合や、特定の場所にプロファイルを作成したい場合は、プロファイルルートディレクトリを変更できます:
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();
}
}
注意: Javaでは、システムプロパティを使用してログレベルを設定することもできます:
プロパティキー: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
プロパティ値: プロファイルルートディレクトリへのパスを表す文字列
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()
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
特別な機能
アドオン
Chromeとは異なり、Firefoxの拡張機能はCapabilityの一部として追加されるのではなく、ドライバーの起動後に作成されます。
Chromeとは異なり、Firefoxの拡張機能はこの問題に記載されているように、機能の一部として追加されるのではなく、ドライバーの起動後に作成されます。
T以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
インストール
Mozilla Add-Onsページ から取得する署名付きxpiファイル
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();
});
});
アンインストール
アドオンをアンインストールするには、そのIDを知る必要があります。 IDはアドオンインストール時の戻り値から取得できます。
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()
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();
});
});
署名なしのインストール
未完成または未公開の拡張機能を使用する場合、署名されていない可能性があります。 そのため、“一時的なもの” としてのみインストールできます。 これは、zipファイルまたはディレクトリを渡すことで実行できます。ディレクトリの例を次に示します。
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()
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();
}
}
}
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();
});
});
ページ全体のスクリーンショット
以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
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
コンテキスト
以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
((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特有の機能
As of June 2022, Selenium officially no longer supports standalone Internet Explorer. The Internet Explorer driver still supports running Microsoft Edge in “IE Compatibility Mode.”
Special considerations
The IE Driver is the only driver maintained by the Selenium Project directly. While binaries for both the 32-bit and 64-bit versions of Internet Explorer are available, there are some known limitations with the 64-bit driver. As such it is recommended to use the 32-bit driver.
Additional information about using Internet Explorer can be found on the IE Driver Server page
Options
Starting a Microsoft Edge browser in Internet Explorer Compatibility mode with basic defined options looks like this:
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
As of Internet Explorer Driver v4.5.0:
- If IE is not present on the system (default in Windows 11), you do not need to use the two parameters above. IE Driver will use Edge and will automatically locate it.
- If IE and Edge are both present on the system, you only need to set attaching to Edge, IE Driver will automatically locate Edge on your system.
So, if IE is not on the system, you only need:
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)
Here are a few common use cases with different capabilities:
fileUploadDialogTimeout
環境によっては、ファイルアップロードダイアログを開くときにInternet Explorerがタイムアウトする場合があります。 IEDriverのデフォルトのタイムアウトは1000ミリ秒ですが、fileUploadDialogTimeout capabilityを使用してタイムアウトを増やすことができます。
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の実行中のすべてのインスタンスのキャッシュ、ブラウザー履歴、およびCookieがクリアされます。
デフォルトでは、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
に設定すると、テストが不安定になったり、応答しなくなったり、
ブラウザがハングしたりする場合があります。
ただし、これはまだ2番目に良い選択であり、最初の選択は 常に
各ゾーンの保護モード設定を手動で実際に設定することです。
ユーザーがこのプロパティを使用している場合、「ベストエフォート」のみがサポートされます。
このケイパビリティは、ブール値をパラメーターとして受け入れます。
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 Command-Line Options
Internet Explorerには、ブラウザーのトラブルシューティングと構成を可能にするいくつかのコマンドラインオプションが含まれています。
次に、サポートされているいくつかのコマンドラインオプションについて説明します。
-private : IEをプライベートブラウジングモードで起動するために使用されます。 これはIE 8以降のバージョンで機能します。
-k : 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
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:
.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()
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
Console output
To change the logging output to display in the console as STDOUT:
.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
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()
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
Log Level
There are 6 available log levels: FATAL
, ERROR
, WARN
, INFO
, DEBUG
, and TRACE
If logging output is specified, the default level is 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");
}
}
}
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
Supporting Files Path
.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");
}
}
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");
}
}
}
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特有の機能
Unlike Chromium and Firefox drivers, the safaridriver is installed with the Operating System. To enable automation on Safari, run the following command from the terminal:
safaridriver --enable
Options
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Safari can be found at Apple’s page About WebDriver for Safari
Starting a Safari session with basic defined options looks like this:
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)
Mobile
Those looking to automate Safari on iOS should look to the Appium project.
Service
Service settings common to all browsers are described on the Service page.
Logging
Unlike other browsers, Safari doesn’t let you choose where logs are output, or change levels. The one option
available is to turn logs off or on. If logs are toggled on, they can be found at:~/Library/Logs/com.apple.WebDriver/
.
.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);
}
}
Note: Java also allows setting console output by System Property;
Property key: SafariDriverService.SAFARI_DRIVER_LOGGING
Property value: "true"
or "false"
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()
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 provides a development version of their browser — Safari Technology Preview To use this version in your code:
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