Chrome 特定功能
默认情况下,Selenium 4与Chrome v75及更高版本兼容. 但是请注意Chrome浏览器的版本与chromedriver的主版本需要匹配.
Options
所有浏览器的通用功能请看这 Options page.
Chrome浏览器的特有功能可以在谷歌的页面找到: 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
参数用于启动浏览器时要使用的命令行开关列表.
有两个很好的资源可以用于研究这些参数:
常用的参数包括 --start-maximized
, --headless=new
以及 --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);
}
}
}
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
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文件. 至于解压的目录,
请使用 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将在驱动过程结束后保持浏览器的打开状态.
添加一个布尔值到选项中:
Note: This is already the default behavior in 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()
Note: This is already the default behavior in .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 源码
设置排除参数至选项中:
/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 对象的示例, 以及用于设置驱动程序位置和端口 可以参考 驱动服务 页面.
日志输出
获取驱动程序日志有助于调试问题. 使用 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
命令行输出
更改日志记录输出以在控制台中显示为标准输出:
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
and $stderr
are both valid values
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
日志级别
共有六种日志级别: 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 一起使用. 请注意, 这是一项不受支持的功能, 并且不会调查 bug.
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
特殊功能
Casting
你可以驱动 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
网络条件
您可以模拟各种网络条件.
以下示例适用于本地 webdrivers. 针对远程 webdrivers, 请参考 Remote 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
DevTools
详见 Chrome DevTools 部分以获取有关使用Chrome DevTools的更多信息