各ブラウザにはカスタム機能とユニークな特徴があります。
これは、このセクションの複数ページの印刷可能なビューです。 印刷するには、ここをクリックしてください.
対応ブラウザ
- 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セッションを開始する場合は、次のようになります:
}
/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeTest {
public ChromeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void headlessOptions() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@Test
public void keepBrowserOpen() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
driver = new ChromeDriver(options);
/examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers {
[TestClass]
public class ChromeTest : BaseTest {
[TestMethod]
public void BasicOptions() {
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void HeadlessOptions() {
var options = new ChromeOptions();
options.AddArgument("--headless=new");
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallAddon()
{
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);
}
}
}
@driver = Selenium::WebDriver.for :chrome, options: options
end
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
引数
args
パラメータは、ブラウザを起動する際に使用するコマンドラインスイッチのリストです。これらの引数を調査するための優れたリソースが2つあります:
一般的に使用されるargsには以下が含まれます:--start-maximized
, --headless=new
and --user-data-dir=...
オプションに引数を追加:
/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeTest {
public ChromeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void headlessOptions() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@Test
public void keepBrowserOpen() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
}
/examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers {
[TestClass]
public class ChromeTest : BaseTest {
[TestMethod]
public void BasicOptions() {
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void HeadlessOptions() {
var options = new ChromeOptions();
options.AddArgument("--headless=new");
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallAddon()
{
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);
}
}
}
@driver.get('https://www.google.com')
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
指定したロケーションでブラウザを起動する
binary
パラメーターは、使用するブラウザの別のロケーションのパスを取ります。
このパラメーターを使用すると、chromedriver を使用して、さまざまな Chromium ベースのブラウザを駆動できます。
オプションにブラウザのロケーションを追加します。
/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeTest {
public ChromeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void headlessOptions() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@Test
public void keepBrowserOpen() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
}
}
def exclude_switches():
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers {
[TestClass]
public class ChromeTest : BaseTest {
[TestMethod]
public void BasicOptions() {
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void HeadlessOptions() {
var options = new ChromeOptions();
options.AddArgument("--headless=new");
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallAddon()
{
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);
}
}
}
it 'Exclude switches' do
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
拡張機能を追加する
extensions
パラメーターはcrxファイルを受け入れます
The extensions
パラメータはcrxファイルを受け入れます。解凍されたディレクトリについては、代わりに load-extension
引数を使用してください。この投稿で述べたように。
オプションに拡張機能を追加します。
/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeTest {
public ChromeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void headlessOptions() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@Test
public void keepBrowserOpen() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Browsers {
[TestClass]
public class ChromeTest : BaseTest {
[TestMethod]
public void BasicOptions() {
var options = new ChromeOptions();
driver = new ChromeDriver(options);
}
[TestMethod]
public void HeadlessOptions() {
var options = new ChromeOptions();
options.AddArgument("--headless=new");
driver = new ChromeDriver(options);
}
[TestMethod]
public void InstallAddon()
{
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);
}
}
}
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
ブラウザを開いたままにする
detach
パラメータをtrueに設定すると、ドライバープロセスが終了した後もブラウザを開いたままにできます。
注意: これはすでにJavaのデフォルトの動作です。
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
注意: これはすでに.NETのデフォルトの動作です。
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
引数を除外する
Chrome はさまざまな引数を追加します。
これらの引数を追加したくない場合は、それらを excludeSwitches
に渡します。
一般的な例は、ポップアップブロッカーをオンに設定することです。
デフォルトの引数の完全なリストは、 Chromium Source Codeから解析できます。
オプションに除外された引数を設定します。
/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeTest {
public ChromeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void headlessOptions() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
}
@Test
public void keepBrowserOpen() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
driver = new ChromeDriver(service);
examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
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 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;
}
}
}
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
/examples/javascript/test/browser/chromeSpecificCaps.spec.js
const Chrome = require('selenium-webdriver/chrome');
const {suite} = require('selenium-webdriver/testing');
const {Browser} = require("selenium-webdriver");
const options = new Chrome.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.google.com');
// 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 = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
it('Basic Chrome test', async function () {
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.CHROME]});
サービス
デフォルトのServiceオブジェクトを作成するための例や、ドライバーの場所とポートを設定する方法は、Driver Serviceページにあります。
ログ出力
ドライバーログを取得することは、問題のデバッグに役立ちます。Serviceクラスを使用すると、ログの出力先を指定できます。ユーザーがどこかにログを指示しない限り、ログ出力は無視されます。
ファイル出力
ログ出力を特定のファイルに保存するように変更するには:
ChromeDriverService service = new ChromeDriverService.Builder()
.withAppendLog(true)
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、システムプロパティによってファイル出力を設定することもできます:
プロパティキー: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
プロパティ値: ログファイルへのパスを表す文字列
driver = webdriver.Chrome(service=service)
examples/python/tests/browsers/test_chrome.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.ChromeOptions()
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.chrome.service.Service(log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.chrome.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.chrome.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.chrome.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.chrome.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Chrome(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()
{
examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
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 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;
}
}
}
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
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
end
コンソール出力
ログ出力をコンソールにSTDOUTとして表示するように変更するには:
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、システムプロパティによってコンソール出力を設定することもできます。
プロパティキー: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
プロパティ値: DriverService.LOG_STDOUT
または DriverService.LOG_STDERR
driver = webdriver.Chrome(service=service)
examples/python/tests/browsers/test_chrome.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.ChromeOptions()
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.chrome.service.Service(log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.chrome.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.chrome.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.chrome.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.chrome.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Chrome(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()
$stdout
と $stderr
はどちらも有効な値です。
examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
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
end
ログレベル
利用可能なログレベルは6つあります:ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, そして OFF
。--verbose
は --log-level=ALL
と同等であり、--silent
は --log-level=OFF
と同等であることに注意してください。このため、この例ではログレベルを一般的に設定しています:
private File getLogLocation() throws IOException {
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、システムプロパティによってログレベルを設定することもできます:
プロパティキー: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
プロパティ値: ChromiumDriverLogLevel
列挙型の文字列表現
driver = webdriver.Chrome(service=service)
examples/python/tests/browsers/test_chrome.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.ChromeOptions()
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.chrome.service.Service(log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.chrome.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.chrome.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.chrome.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.chrome.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Chrome(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()
@driver = Selenium::WebDriver.for :chrome, service: service
examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
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
end
ログファイル機能
ファイルにログを記録する際にのみ利用できる2つの機能があります:
- ログの追加
- 読みやすいタイムスタンプ
これらを使用するには、ログパスとログレベルも明示的に指定する必要があります。ログ出力はプロセスではなくドライバーによって管理されるため、若干の違いが見られる場合があります。
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、これらの機能をシステムプロパティによって切り替えることもできます:
プロパティキー: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY
およびChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
プロパティ値: "true"
または "false"
examples/python/tests/browsers/test_chrome.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.ChromeOptions()
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.chrome.service.Service(log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.chrome.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.chrome.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.chrome.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.chrome.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Chrome(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()
examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
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
end
ビルドチェックの無効化
ChromedriverとChromeブラウザのバージョンは一致する必要があり、一致しない場合、ドライバーはエラーを返します。ビルドチェックを無効にすると、任意のバージョンのChromeでドライバーを強制的に使用できます。ただし、これはサポートされていない機能であり、バグは調査されません。
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、システムプロパティによってビルドチェックを無効にすることもできます:
プロパティキー: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
プロパティ値: "true"
または "false"
examples/python/tests/browsers/test_chrome.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_args():
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.ChromeOptions()
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.chrome.service.Service(log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as fp:
assert "Starting ChromeDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.chrome.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Chrome(service=service)
out, err = capfd.readouterr()
assert "Starting ChromeDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.chrome.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.chrome.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Chrome(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.chrome.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Chrome(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()
{
examples/dotnet/SeleniumDocs/Browsers/ChromeTest.cs
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 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;
}
}
}
examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.chrome
options.detach = true
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.chrome
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
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
end
特別な機能
一部のブラウザは、それぞれに特有の追加機能を実装しています。
キャスティング
Chrome Castデバイスを操作することができ、タブの共有も含まれます。
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
ネットワークの状態
さまざまなネットワークの状態をシミュレートできます。
以下の例はローカルWebDriver用です。リモートWebDriverについては、リモートWebDriverページを参照してください。
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
ログ
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
パーミッション
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_chrome.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
def test_basic_options():
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
def test_keep_browser_open():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def test_headless():
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
def exclude_switches():
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(options=chrome_options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/chrome_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Chrome' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Keep browser open' do
options = Selenium::WebDriver::Options.chrome(detach: true)
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
it 'Exclude switches' do
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
@driver = Selenium::WebDriver.for :chrome, options: options
@driver.get('https://www.google.com')
end
end
デベロッパー ツール
Chromeデベロッパーツールの使用に関する詳細については、[Chromeデベロッパー ツール] セクションを参照してください。
2 - Edge固有の機能
Microsoft EdgeはChromiumで実装されており、サポートされている最も古いバージョンはv79です。 Chromeと同様に、edgedriverのメジャー バージョン番号は、Edgeブラウザのメジャーバージョンと一致する必要があります。
Chromeページ にあるすべての機能とオプションは、Edgeでも機能します。
オプション
すべてのブラウザに共通する機能はオプション ページに記載されています。
Chromiumに特有の機能は、GoogleのCapabilities & ChromeOptionsページに文書化されています。
基本的な定義済みオプションを使用して Edgeセッションを開始すると、次のようになります。
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
@driver = Selenium::WebDriver.for :edge, options: options
end
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
let options = new edge.Options();
driver = await env.builder()
.setEdgeOptions(options)
.setEdgeService(new edge.ServiceBuilder(edgedriver.binPath()))
.build();
/examples/javascript/test/getting_started/openEdgeTest.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edgedriver = require('@sitespeed.io/edgedriver');
const edge = require('selenium-webdriver/edge');
suite(function (env) {
describe('Open Edge', function () {
let driver;
before(async function () {
let options = new edge.Options();
driver = await env.builder()
.setEdgeOptions(options)
.setEdgeService(new edge.ServiceBuilder(edgedriver.binPath()))
.build();
});
after(async () => await driver.quit());
it('Basic Edge test', async function () {
await driver.get('https://www.google.com');
});
});
}, { browsers: [Browser.EDGE]});
引数
args
パラメータは、ブラウザを起動する際に使用されるコマンドラインスイッチのリストです。これらの引数を調査するための優れたリソースが2つあります:
一般的に使用される引数には、--start-maximized
および --headless=new
が含まれます。 and --user-data-dir=...
オプションに引数を追加します。
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
end
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
指定された場所でブラウザを起動する
binary
パラメータは、使用するブラウザの代替位置のパスを指定します。このパラメータを使用すると、chromedriverを利用してさまざまなChromiumベースのブラウザを操作できます。
オプションにブラウザの場所を追加する:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
拡張機能を追加する
extensions
パラメータは、crxファイルを受け入れます。展開されたディレクトリについては、load-extension
引数を使用してください。このことはこの投稿で言及されています。
オプションに拡張機能を追加する:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
ブラウザを開いたままにする
detach
パラメータをtrue に設定すると、プロセスが終了した後でもブラウザが開いたままになります。ただし、quit コマンドがドライバーに送信されない限り、ブラウザは開いたままになります。
注意: これはすでにJavaのデフォルトの動作です。
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
注意: これはすでに.NETのデフォルトの動作です。
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
引数を除外する
MSEdgedriverには、ブラウザを起動するために使用されるいくつかのデフォルト引数があります。それらの引数を追加したくない場合は、excludeSwitches
に渡してください。一般的な例は、ポップアップブロッカーを再度オンにすることです。デフォルト引数の完全なリストはChromium Source Codeから解析できます。
オプションに除外された引数を設定する:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.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 = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
サービス
デフォルトのサービスオブジェクトを作成するための例や、ドライバの場所とポートを設定する例は、Driver Service ページにあります。
ログ出力
ドライバのログを取得することは、問題をデバッグするのに役立ちます。サービスクラスを使用すると、ログの出力先を指定できます。ユーザーがどこかにログを指示しない限り、ログ出力は無視されます。
ファイル出力
特定のファイルに保存するようにログ出力を変更するには、以下のようにします:
.withAppendLog(true)
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでもシステムプロパティを使用してファイル出力を設定できます:
プロパティキー: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
プロパティ値: ログファイルのパスを表す文字列
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
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.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(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.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=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.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=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()
{
examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
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 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;
}
}
}
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
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
end
コンソール出力
ログ出力をコンソールにSTDOUTとして表示するには:
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注: Javaでは、システムプロパティを使用してコンソール出力を設定することもできます。
プロパティキー: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
プロパティ値:DriverService.LOG_STDOUT
または DriverService.LOG_STDERR
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
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.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(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.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=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.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=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()
$stdout
と $stderr
はどちらも有効な値です。
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
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
end
ログレベル
利用可能なログレベルは6つあります:ALL
, DEBUG
, INFO
, WARNING
, SEVERE
および OFF
。--verbose
は --log-level=ALL
と同等であり、--silent
は--log-level=OFF
と同等です。したがって、この例ではログレベルを一般的に設定しています:
Assertions.assertTrue(fileContent.contains(expected));
}
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、システムプロパティを使用してログレベルを設定することもできます:
プロパティキー: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
プロパティ値:ChromiumDriverLogLevel
列挙型の文字列表現
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
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.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(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.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=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.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=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()
@driver = Selenium::WebDriver.for :edge, service: service
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
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
end
ログファイルの機能
ファイルにログを記録する際にのみ利用可能な2つの機能があります:
- ログの追加
- 読みやすいタイムスタンプ
これらを使用するには、ログパスとログレベルも明示的に指定する必要があります。ログ出力はプロセスではなくドライバによって管理されるため、若干の違いが見られることがあります。
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Javaでは、これらの機能をSystem Propertyによって切り替えることもできます:
プロパティキー:EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY
および EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
プロパティ値: "true"
または "false"
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
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.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(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.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=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.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=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()
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
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
end
ビルドチェックの無効化
Edge ブラウザとmsedgedriverのバージョンは一致する必要があり、一致しない場合はドライバにエラーが表示されます。ビルドチェックを無効にすると、任意のバージョンのEdgeでドライバを強制的に使用できます。 この機能はサポートされていないことに注意してください。バグは調査されません。
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注: Javaでは、システムプロパティを使用してビルドチェックを無効にすることもできます:
プロパティキー:EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
プロパティ値: "true"
または "false"
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
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.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(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.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=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.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=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()
{
examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
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 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;
}
}
}
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
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 << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
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
end
Internet Explorer Compatibility モード
Microsoft Edge は、Internet Explorer ドライバークラスを Microsoft Edgeと組み合わせて使用する “Internet Explorer 互換モード"で動かすことができます。 詳細については、Internet Explorerページを参照してください。
特別な機能
一部のブラウザは、それぞれ特有の追加機能を実装しています。
キャスティング
Edge を使用して Chrome Cast デバイスを操作し、タブを共有することができます。
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
ネットワーク条件
さまざまなネットワーク条件をシミュレートすることができます。
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
ログ
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
権限
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().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 {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
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(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
DevTools
EdgeでDevToolsを使用する際の詳細については、[Chrome DevTools]セクションを参照してください。
3 - Firefox特有の機能
Selenium 4 には Firefox 78 以降が必要です。 常に最新バージョンの geckodriver を使用することをお勧めします。
オプション
全ブラウザに共通のCapabilityについては、オプションページで説明しています。
Firefox に固有のCapabilityは、Mozilla のページの firefoxOptions にあります。
基本的な定義済みのオプションを使用して Firefox セッションを開始すると、以下のようになります。
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
driver = webdriver.Firefox(options=options)
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
@driver = Selenium::WebDriver.for :firefox, options: options
end
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
let options = new firefox.Options();
driver = await env.builder()
.setFirefoxOptions(options)
.build();
/examples/javascript/test/getting_started/openFirefoxTest.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const firefox = require('selenium-webdriver/firefox');
suite(function (env) {
describe('Open Firefox', function () {
let driver;
before(async function () {
let options = new firefox.Options();
driver = await env.builder()
.setFirefoxOptions(options)
.build();
});
after(async () => await driver.quit());
it('Basic Firefox test', async function () {
await driver.get('https://www.google.com');
});
});
}, { browsers: [Browser.FIREFOX]});
さまざまなCapabilityを備えた一般的な使用例をいくつか示します。
引数
args
パラメータは、ブラウザの起動時に使用するコマンドラインスイッチのリストです。
一般的に使用される引数には、 -headless
と "-profile"
、"/path/to/profile"
が含まれます。
オプションに引数を追加します。
driver.uninstallExtension(id);
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
public void UnInstallAddon()
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env.builder()
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.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 = await env.builder().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 = await env.builder().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();
});
});
}, { browsers: [Browser.FIREFOX]});
指定したロケーションでブラウザを起動する
binary
パラメーターは、使用するブラウザーの別のロケーションのパスを取ります。
たとえば、このパラメーターを使用すると、geckodriver を使用して、製品版とFirefox Nightlyの両方がコンピューターに存在する場合、
製品版の代わりに Firefox Nightly を駆動できます 。
オプションにブラウザーのロケーションを追加します。
driver.installExtension(path, true);
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
driver.uninstall_addon(extension_id)
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
プロファイル
Firefoxプロファイルを操作するにはいくつかの方法があります。
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
var options = new FirefoxOptions();
var profile = new FirefoxProfile();
options.Profile = profile;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
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に記載されています。
ログ出力
ドライバーログを取得することは、さまざまな問題のデバッグに役立ちます。サービスクラスを使用すると、ログの保存先を指定できます。ログ出力は、ユーザーがどこかに指定しない限り無視されます。
ファイル出力
特定のファイルにログ出力を保存するには:
System.setOut(new PrintStream(getLogLocation()));
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.*;
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.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver 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 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
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
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 = startDriver();
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 = startDriver();
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());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
注: Java では、システムプロパティによってファイル出力を設定することもできます。
プロパティキー:GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
プロパティ値: ログファイルへのパスを表す文字列
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
@driver = Selenium::WebDriver.for :firefox, service: service
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
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
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('../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('../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('../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
end
end
コンソール出力
ログ出力をコンソールに表示するには、以下のようにします:
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.*;
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.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver 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 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
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
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 = startDriver();
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 = startDriver();
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());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
注意: Javaは、システムプロパティを使用してコンソール出力を設定することもできます;
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
プロパティ値: DriverService.LOG_STDOUT
または DriverService.LOG_STDERR
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
@driver = Selenium::WebDriver.for :firefox, service: service
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
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
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('../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('../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('../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
end
end
ログレベル
利用可能なログレベルは7つあります: fatal
, error
, warn
, info
, config
, debug
, trace
。
ロギングが指定されている場合、デフォルトのレベルは info
になります。
-v
iは -log debug
と同等であり、-vv
は log trace
と同等です。
したがって、この例は一般的にログレベルを設定するためのものです:
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.*;
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.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver 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 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
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
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 = startDriver();
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 = startDriver();
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());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
注意: Javaは、システムプロパティによってログレベルの設定も可能です:
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
プロパティ値:FirefoxDriverLogLevel
列挙型の文字列表現
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
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
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('../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('../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('../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
end
end
トランケートログ
ドライバーは、大きなバイナリの文字列表現を含む、送信されたすべてのものをログに記録します。そのため、Firefoxではデフォルトで行が切り捨てられます。切り捨てを無効にするには:
@Test
public void setProfileLocation() throws IOException {
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.*;
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.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver 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 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
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
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 = startDriver();
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 = startDriver();
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());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
注意: Javaでは、システムプロパティによってログレベルを設定することもできます。
プロパティキー: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
プロパティ値: "true"
または "false"
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
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
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('../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('../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('../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
end
end
プロファイルルート
プロファイルのデフォルトディレクトリは、システムの一時ディレクトリです。そのディレクトリにアクセスできない場合や、特定の場所にプロファイルを作成したい場合は、プロファイルルートディレクトリを変更できます:
@Test
public void installAddon() {
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.*;
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.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver 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 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
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().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(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
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 = startDriver();
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 = startDriver();
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());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
注意: Javaでは、システムプロパティを使用してログレベルを設定することもできます:
プロパティキー: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
プロパティ値: プロファイルルートディレクトリへのパスを表す文字列
examples/python/tests/browsers/test_firefox.py
import os
import subprocess
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()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_to_file(log_path):
service = webdriver.firefox.service.Service(log_path=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()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_to_stdout(capfd):
service = webdriver.firefox.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
@pytest.mark.skip(reason="broken in 4.10 fixed in 4.11")
def test_log_level(log_path):
service = webdriver.firefox.service.Service(service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_truncation(log_path):
service = webdriver.firefox.service.Service(service_args=['--log-no-truncate', '--log', 'debug'], log_path=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.firefox.service.Service(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):
driver = firefox_driver
driver.install_addon(addon_path)
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):
driver = firefox_driver
id = driver.install_addon(addon_path)
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):
driver = firefox_driver
driver.install_addon(addon_path, 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"
it 'installs addon' do
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
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
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('../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('../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('../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
end
end
特別な機能
アドオン
Chromeとは異なり、Firefoxの拡張機能はCapabilityの一部として追加されるのではなく、ドライバーの起動後に作成されます。
Chromeとは異なり、Firefoxの拡張機能はこの問題に記載されているように、機能の一部として追加されるのではなく、ドライバーの起動後に作成されます。
T以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
インストール
Mozilla Add-Onsページ から取得する署名付きxpiファイル
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
await driver.uninstallAddon(id);
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.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 = await env.builder().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 = await env.builder().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();
});
});
}, { browsers: [Browser.FIREFOX]});
アンインストール
アドオンをアンインストールするには、そのIDを知る必要があります。 IDはアドオンインストール時の戻り値から取得できます。
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.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 = await env.builder().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 = await env.builder().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();
});
});
}, { browsers: [Browser.FIREFOX]});
署名なしのインストール
未完成または未公開の拡張機能を使用する場合、署名されていない可能性があります。 そのため、“一時的なもの” としてのみインストールできます。 これは、zipファイルまたはディレクトリを渡すことで実行できます。ディレクトリの例を次に示します。
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
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()
{
driver = new FirefoxDriver();
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);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.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 = await env.builder().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 = await env.builder().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();
});
});
}, { browsers: [Browser.FIREFOX]});
ページ全体のスクリーンショット
以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
コンテキスト
以下の例はローカルWebDriver用です。リモートWebDriverについては、Remote WebDriverページを参照してください。
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
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 = new FirefoxDriver();
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 = new FirefoxDriver();
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());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../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('../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('../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 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
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:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
driver = webdriver.Ie(options=options)
driver.quit()
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.EnsureCleanSession = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.IgnoreZoomLevel = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalInternetExplorerOption("silent", true);
IWebDriver driver = new InternetExplorerDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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();
}
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
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";
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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();
}
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
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";
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
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())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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(System.getProperty("webdriver.edge.binary"));
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;
}
}
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
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
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_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=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.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(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.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@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
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)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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(System.getProperty("webdriver.edge.binary"));
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;
}
}
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
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
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_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=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.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(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.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@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
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)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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(System.getProperty("webdriver.edge.binary"));
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;
}
}
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
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
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_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=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.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(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.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
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 = Environment.GetEnvironmentVariable("EDGE_BINARY");
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());
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 = 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;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@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
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())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
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(System.getProperty("webdriver.edge.binary"));
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;
}
}
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
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_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=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.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(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.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LibraryExtractionPath = GetTempDirectory();
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
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 = Environment.GetEnvironmentVariable("EDGE_BINARY");
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());
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 = 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;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@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
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:
}
/examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
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.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
}
def test_basic_options():
options = SafariOptions()
/examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.safari.options import Options as SafariOptions
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/SafariTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Safari;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("OSX")]
public class SafariTest
{
[TestMethod]
public void BasicOptions()
{
var options = new SafariOptions();
var driver = new SafariDriver(options);
driver.Quit();
}
}
}
@driver = Selenium::WebDriver.for :safari, options: options
end
/examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
/examples/javascript/test/browser/safariSpecificCap.spec.js
const safari = require('selenium-webdriver/safari');
const {Browser} = require("selenium-webdriver");
const { suite } = require('selenium-webdriver/testing')
const options = new safari.Options();
const process = require('node:process');
suite(function(env) {
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.SAFARI]});
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)
examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
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);
}
}
Note: Java also allows setting console output by System Property;
Property key: SafariDriverService.SAFARI_DRIVER_LOGGING
Property value: "true"
or "false"
service = webdriver.safari.service.Service(service_args=["--diagnose"])
examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.safari.options.Options()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.safari.service.Service(service_args=["--diagnose"])
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.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
service.args << '--diagnose'
examples/ruby/spec/browsers/safari_spec.rb
# 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 'enable 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
Safari Technology Preview
Apple provides a development version of their browser — Safari Technology Preview To use this version in your code:
examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
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);
}
}
options = webdriver.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.safari.options.Options()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.safari.service.Service(service_args=["--diagnose"])
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.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
examples/ruby/spec/browsers/safari_spec.rb
# 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 'enable 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