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デベロッパー ツール] セクションを参照してください。