每个浏览器都有定制和特有的功能。
支持的浏览器列表
1 - 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的更多信息
2 - Edge 特定功能
微软Edge是用Chromium实现的, 最早支持版本是v79. 与Chrome类似, Edge驱动的主版本号必须与Edge浏览器的主要版本匹配.
在 Chrome 页面 上找到的所有capabilities和选项也适用于Edge.
选项
所有浏览器的共有功能在 Options 页面.
Chromium独有的功能记录在谷歌的 Capabilities & ChromeOptions
使用基本定义的选项启动 Edge 会话如下所示:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
@driver = Selenium::WebDriver.for :edge, options: options
end
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
let options = new edge.Options();
driver = await env.builder()
.setEdgeOptions(options)
.setEdgeService(new edge.ServiceBuilder(edgedriver.binPath()))
.build();
/examples/javascript/test/getting_started/openEdgeTest.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edgedriver = require('@sitespeed.io/edgedriver');
const edge = require('selenium-webdriver/edge');
suite(function (env) {
describe('Open Edge', function () {
let driver;
before(async function () {
let options = new edge.Options();
driver = await env.builder()
.setEdgeOptions(options)
.setEdgeService(new edge.ServiceBuilder(edgedriver.binPath()))
.build();
});
after(async () => await driver.quit());
it('Basic Edge test', async function () {
await driver.get('https://www.google.com');
});
});
}, { browsers: [Browser.EDGE]});
参数
args
参数用于列出启动浏览器时使用的命令行开关.
有两个很好的资源可用于研究这些参数:
常用参数包括 --start-maximized
、 --headless=new
和 --user-data-dir=...
为options添加参数:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
driver.quit()
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
end
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
在指定位置启动浏览器
binary
参数包含要使用的浏览器备用位置的路径.
使用此参数, 您可以使用 chromedriver 驱动各种基于 Chromium 的浏览器.
在options中添加浏览器位置:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
添加扩展
extensions
参数接受 crx 文件.
至于已解压的目录、中提到,
请使用本文中提及的 load-extension
.
在options中添加扩展:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
保持浏览器打开
将 detach
参数设置为 true后,
只要不向driver发送退出命令,
就可以在进程结束后保持浏览器打开.
Note: This is already the default behavior in Java.
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
Note: This is already the default behavior in .NET.
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
排除参数
MSEdgedriver 有几个用于启动浏览器的默认参数.
如果不希望添加这些参数, 可将它们传递到 excludeSwitches
中.
一个常见的例子就是重新打开弹出窗口拦截器.
默认参数的完整列表参考
Chromium Source Code
在options中设置排除参数:
/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public EdgeDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void headlessOptions() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
}
[TestMethod]
public void HeadlessOptions()
{
var options = new EdgeOptions();
options.AddArgument("--headless=new");
var driver = new EdgeDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
.build();
/examples/javascript/test/browser/edgeSpecificCaps.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const edge = require('selenium-webdriver/edge');
const options = new edge.Options();
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.addArguments('--headless=new'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('exclude switches', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.excludeSwitches('enable-automation'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Keep browser open - set detach to true ', async function () {
let driver = await env
.builder()
.setEdgeOptions(options.detachDriver(true))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
// As tests runs in ci, quitting the driver instance to avoid any failures
await driver.quit();
});
it('Basic edge test', async function () {
const Options = new edge.Options();
let driver = await env
.builder()
.setEdgeOptions(Options)
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
});
}, { browsers: [Browser.EDGE]});
服务
创建默认服务对象, 设置驱动程序位置和端口的示例可以参考 Driver服务 页面.
日志输出
获取驱动程序日志有助于调试问题。 服务类可让您配置日志的输出。 日志输出会被忽略, 除非用户显示指定.
文件输出
更改日志输出以保存到特定文件:
.withAppendLog(true)
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Java同样允许在系统属性中配置文件输出:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
{
examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
}
}
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
end
控制台输出
要更改日志输出, 使其在控制台中显示为标准输出:
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Java同样允许在系统属性中配置控制台输出:
属性键: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
属性值: DriverService.LOG_STDOUT
或 DriverService.LOG_STDERR
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
$stdout
and $stderr
are both valid values
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
end
日志级别
有 6 种可用的日志级别: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, 以及 OFF
.
请注意, --verbose
等同于 --log-level=ALL
, 而 --silent
等同于 --log-level=OFF
,
因此, 本例只是一般性地设置日志级别:
Assertions.assertTrue(fileContent.contains(expected));
}
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Java同样允许在系统属性中配置日志级别:
属性键: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
属性值: String representation of ChromiumDriverLogLevel
enum
driver = webdriver.Edge(service=service)
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
@driver = Selenium::WebDriver.for :edge, service: service
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
end
日志文件功能
有 2 项功能只有在记录到文件时才可用:
- 追加日志
- 可读时间戳
要使用它们, 还需要明确指定日志路径和日志级别. 日志输出将由driver而非进程管理, 因此可能会出现细微差别.
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Java同样允许在系统属性中配置开闭这些功能:
属性键: EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY
以及 EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
属性值: "true"
或 "false"
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
end
禁用构建检查
Edge 浏览器和 msedgedriver 版本应该匹配, 如果不匹配, 驱动程序就会出错. 如果禁用构建检查, 则可以强制驱动程序与任何版本的 Edge 一起使用. 请注意, 这是一项不受支持的功能, 而且不会对错误进行调查.
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
注意: Java同样允许在系统属性中配置禁用构建检查:
属性键: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
属性值: "true"
或 "false"
examples/python/tests/browsers/test_edge.py
import re
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_args():
options = webdriver.EdgeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_keep_browser_open():
options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_exclude_switches():
options = webdriver.EdgeOptions()
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
def test_log_to_file(log_path):
service = webdriver.edge.service.Service(log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as fp:
assert "Starting Microsoft Edge WebDriver" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.edge.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Edge(service=service)
out, err = capfd.readouterr()
assert "Starting Microsoft Edge WebDriver" in out
driver.quit()
def test_log_level(log_path):
service = webdriver.edge.service.Service(service_args=['--log-level=DEBUG'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert '[DEBUG]' in f.read()
driver.quit()
def test_log_features(log_path):
service = webdriver.edge.service.Service(service_args=['--append-log', '--readable-timestamp'], log_path=log_path)
driver = webdriver.Edge(service=service)
with open(log_path, 'r') as f:
assert re.match("\[\d\d-\d\d-\d\d\d\d", f.read())
driver.quit()
def test_build_checks(log_path):
service = webdriver.edge.service.Service(service_args=['--disable-build-check'], log_path=log_path)
driver = webdriver.Edge(service=service)
expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check"
with open(log_path, 'r') as f:
assert expected in f.read()
driver.quit()
{
examples/dotnet/SeleniumDocs/Browsers/EdgeTest.cs
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class EdgeTest
{
private EdgeDriver driver;
private string _logLocation;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new EdgeOptions();
driver = new EdgeDriver(options);
}
[TestMethod]
public void Arguments()
{
var options = new EdgeOptions();
options.AddArgument("--start-maximized");
driver = new EdgeDriver(options);
}
[TestMethod]
public void InstallExtension()
{
var options = new EdgeOptions();
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.crx");
options.AddExtension(extensionFilePath);
driver = new EdgeDriver(options);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void ExcludeSwitch()
{
var options = new EdgeOptions();
options.AddExcludedArgument("disable-popup-blocking");
driver = new EdgeDriver(options);
}
[TestMethod]
public void LogsToFile()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Starting Microsoft Edge WebDriver")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = EdgeDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new EdgeDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsLevel()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
// service.LogLevel = ChromiumDriverLogLevel.Debug
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("[DEBUG]:")));
}
[TestMethod]
[Ignore("Not implemented")]
public void ConfigureDriverLogs()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.EnableAppendLog = true;
// service.readableTimeStamp = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
var regex = new Regex(@"\[\d\d-\d\d-\d\d\d\d");
Assert.IsNotNull(lines.FirstOrDefault(line => regex.Matches("").Count > 0));
}
[TestMethod]
public void DisableBuildCheck()
{
var service = EdgeDriverService.CreateDefaultService();
service.LogPath = GetLogLocation();
service.EnableVerboseLogging = true;
service.DisableBuildCheck = true;
driver = new EdgeDriver(service);
driver.Quit(); // Close the Service log file before reading
var expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains(expected)));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
}
}
examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge
options.args << '--maximize'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'keeps browser open' do
options = Selenium::WebDriver::Options.edge
options.detach = true
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
it 'excludes switches' do
options = Selenium::WebDriver::Options.edge
options.exclude_switches << 'enable-automation'
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
describe 'Service' do
let(:file_name) { File.expand_path('msedgedriver.log') }
after { FileUtils.rm_f(file_name) }
it 'logs to file' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).first).to include('Starting Microsoft Edge WebDriver')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.edge
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :edge, service: service
}.to output(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.edge
service.log = file_name
service.args << '--log-level=DEBUG'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).to eq true
end
it 'sets log features' do
args = ["--log-path=#{file_name}", '--verbose']
service = Selenium::WebDriver::Service.edge(args: args)
service.args << '--append-log'
service.args << '--readable-timestamp'
@driver = Selenium::WebDriver.for :edge, service: service
expect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).to eq true
end
it 'disables build checks' do
service = Selenium::WebDriver::Service.edge log: file_name, args: ['--verbose']
service.args << '--disable-build-check'
@driver = Selenium::WebDriver.for :edge, service: service
warning = /\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/
expect(File.readlines(file_name).grep(warning).any?).to eq true
end
end
end
Internet Explorer 兼容模式
微软Edge可以被"Internet Explorer兼容模式"驱动, 该模式使用Internet Explorer驱动类与微软Edge结合使用. 阅读 Internet Explorer 页面 了解更多详情.
特殊功能
某些浏览器实现了其特有的附加功能.
Cast
您可以使用 Edge 驱动 Chrome Cast 设备, 包括共享标签页
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
网络状况
您可以模拟各种网络状况.
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
日志
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
权限
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
开发者工具
有关在 Edge 中使用 DevTools 的更多信息, 请参阅 [Chrome DevTools] 部分.
3 - Firefox specific functionality
Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver.
Options
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Firefox can be found at Mozilla’s page for firefoxOptions
Starting a Firefox session with basic defined options looks like this:
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
driver = webdriver.Firefox(options=options)
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
@driver = Selenium::WebDriver.for :firefox, options: options
end
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
let options = new firefox.Options();
driver = await env.builder()
.setFirefoxOptions(options)
.build();
/examples/javascript/test/getting_started/openFirefoxTest.spec.js
const {Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const firefox = require('selenium-webdriver/firefox');
suite(function (env) {
describe('Open Firefox', function () {
let driver;
before(async function () {
let options = new firefox.Options();
driver = await env.builder()
.setFirefoxOptions(options)
.build();
});
after(async () => await driver.quit());
it('Basic Firefox test', async function () {
await driver.get('https://www.google.com');
});
});
}, { browsers: [Browser.FIREFOX]});
Here are a few common use cases with different capabilities:
Arguments
The args
parameter is for a list of Command line switches used when starting the browser.
Commonly used args include -headless
and "-profile", "/path/to/profile"
Add an argument to options:
driver.uninstallExtension(id);
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
public void UnInstallAddon()
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
let driver = await env.builder()
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
}, { browsers: [Browser.FIREFOX]});
Start browser in a specified location
The binary
parameter takes the path of an alternate location of browser to use. For example, with this parameter you can
use geckodriver to drive Firefox Nightly instead of the production version when both are present on your computer.
Add a browser location to options:
driver.installExtension(path, true);
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
driver.uninstall_addon(extension_id)
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
Profiles
There are several ways to work with Firefox profiles
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
var options = new FirefoxOptions();
var profile = new FirefoxProfile();
options.Profile = profile;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
let profile = '/path to custom profile';
options.setProfile(profile);
const driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
val options = FirefoxOptions()
options.profile = FirefoxProfile()
driver = RemoteWebDriver(options)
Note: Whether you create an empty FirefoxProfile
or point it to the directory of your own profile, Selenium
will create a temporary directory to store either the data of the new profile or a copy of your existing one. Every
time you run your program, a different temporary directory will be created. These directories are not cleaned up
explicitly by Selenium, they should eventually get removed by the operating system. However, if you want to remove
the copy manually (e.g. if your profile is large in size), the path of the copy is exposed by the FirefoxProfile
object. Check the language specific implementation to see how to retrieve that location.
If you want to use an existing Firefox profile, you can pass in the path to that profile. Please refer to the official Firefox documentation for instructions on how to find the directory of your profile.
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
System.setOut(new PrintStream(getLogLocation()));
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,
FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withTruncatedLogs(false)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
Note: Java also allows setting file output by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
@driver = Selenium::WebDriver.for :firefox, service: service
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\','/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
end
end
Console output
To change the logging output to display in the console:
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,
FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withTruncatedLogs(false)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
Note: Java also allows setting console output by System Property;
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
@driver = Selenium::WebDriver.for :firefox, service: service
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\','/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
end
end
Log level
There are 7 available log levels: fatal
, error
, warn
, info
, config
, debug
, trace
.
If logging is specified the level defaults to info
.
Note that -v
is equivalent to -log debug
and -vv
is equivalent to log trace
,
so this examples is just for setting the log level generically:
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,
FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withTruncatedLogs(false)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of FirefoxDriverLogLevel
enum
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\','/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
end
end
Truncated Logs
The driver logs everything that gets sent to it, including string representations of large binaries, so Firefox truncates lines by default. To turn off truncation:
@Test
public void setProfileLocation() throws IOException {
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,
FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withTruncatedLogs(false)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
Property value: "true"
or "false"
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\','/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
end
end
Profile Root
The default directory for profiles is the system temporary directory. If you do not have access to that directory, or want profiles to be created some place specific, you can change the profile root directory:
@Test
public void installAddon() {
examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
public class FirefoxTest extends BaseTest {
private FirefoxDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void arguments() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
@Test
public void logsToFile() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withLogLevel(FirefoxDriverLogLevel.DEBUG)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));
}
@Test
public void stopsTruncatingLogs() throws IOException {
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,
FirefoxDriverLogLevel.DEBUG.toString());
FirefoxDriverService service = new GeckoDriverService.Builder()
.withTruncatedLogs(false)
.build();
driver = new FirefoxDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertFalse(fileContent.contains(" ... "));
}
@Test
public void setProfileLocation() throws IOException {
FirefoxDriverService service = new GeckoDriverService.Builder()
.withProfileRoot(getTempDirectory())
.build();
driver = new FirefoxDriver(service);
String location = (String) driver.getCapabilities().getCapability("moz:profile");
Assertions.assertTrue(location.contains(getTempDirectory().getAbsolutePath()));
}
@Test
public void installAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = startDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = startDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
public File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("geckodriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("profile-").toFile();
}
return tempDirectory;
}
private FirefoxDriver startDriver() {
FirefoxOptions options = new FirefoxOptions();
options.setImplicitWaitTimeout(Duration.ofSeconds(1));
return new FirefoxDriver(options);
}
}
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
Property value: String representing path to profile root directory
examples/python/tests/browsers/test_firefox.py
import os
import subprocess
import pytest
from selenium import webdriver
def test_basic_options():
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_arguments():
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = webdriver.Firefox(options=options)
driver.quit()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_to_file(log_path):
service = webdriver.firefox.service.Service(log_path=log_path, service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
driver.get("https://www.selenium.dev")
with open(log_path, 'r') as fp:
assert "geckodriver INFO Listening on" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_to_stdout(capfd):
service = webdriver.firefox.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Firefox(service=service)
out, err = capfd.readouterr()
assert "geckodriver INFO Listening on" in out
driver.quit()
@pytest.mark.skip(reason="broken in 4.10 fixed in 4.11")
def test_log_level(log_path):
service = webdriver.firefox.service.Service(service_args=['--log', 'debug'])
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert '\tDEBUG' in f.read()
driver.quit()
@pytest.mark.skip(reason="implemented in 4.11")
def test_log_truncation(log_path):
service = webdriver.firefox.service.Service(service_args=['--log-no-truncate', '--log', 'debug'], log_path=log_path)
driver = webdriver.Firefox(service=service)
with open(log_path, 'r') as f:
assert ' ... ' not in f.read()
driver.quit()
def test_profile_location(temp_dir):
service = webdriver.firefox.service.Service(service_args=['--profile-root', temp_dir])
driver = webdriver.Firefox(service=service)
profile_name = driver.capabilities.get('moz:profile').replace('\\', '/').split('/')[-1]
assert profile_name in os.listdir(temp_dir)
driver.quit()
def test_install_addon(firefox_driver, addon_path):
driver = firefox_driver
driver.install_addon(addon_path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver, addon_path):
driver = firefox_driver
id = driver.install_addon(addon_path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(webdriver.common.by.By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver, addon_path):
driver = firefox_driver
driver.install_addon(addon_path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(webdriver.common.by.By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
it 'installs addon' do
examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox
options.args << '-headless'
@driver = Selenium::WebDriver.for :firefox, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('geckodriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.rm_rf(root_directory)
end
it 'logs to file' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).first).to include("geckodriver\tINFO\tListening on")
end
it 'logs to console' do
service = Selenium::WebDriver::Service.firefox
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :firefox, service: service
}.to output(/geckodriver INFO Listening on/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.firefox
service.log = file_name
service.args += %w[--log debug]
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).to eq true
end
it 'stops truncating log lines' do
service = Selenium::WebDriver::Service.firefox(log: file_name, args: %w[--log debug])
service.args << '--log-no-truncate'
@driver = Selenium::WebDriver.for :firefox, service: service
expect(File.readlines(file_name).grep(/ \.\.\. /).any?).to eq false
end
it 'sets default profile location' do
service = Selenium::WebDriver::Service.firefox
service.args += ['--profile-root', root_directory]
@driver = Selenium::WebDriver.for :firefox, service: service
profile_location = Dir.new(@driver.capabilities['moz:profile'])
expect(profile_location.path.gsub('\\','/')).to include(root_directory)
end
end
describe 'Features' do
let(:driver) { start_firefox }
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
end
end
Special Features
Add-ons
Unlike Chrome, Firefox extensions are not added as part of capabilities as mentioned in this issue, they are created after starting the driver.
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
Installation
A signed xpi file you would get from Mozilla Addon page
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
await driver.uninstallAddon(id);
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
}, { browsers: [Browser.FIREFOX]});
Uninstallation
Uninstalling an addon requires knowing its id. The id can be obtained from the return value when installing the add-on.
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
}, { browsers: [Browser.FIREFOX]});
Unsigned installation
When working with an unfinished or unpublished extension, it will likely not be signed. As such, it can only be installed as “temporary.” This can be done by passing in either a zip file or a directory, here’s an example with a directory:
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/dotnet/SeleniumDocs/Browsers/FirefoxTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumDocs.Browsers
{
[TestClass]
public class FirefoxTest
{
private FirefoxDriver driver;
[TestCleanup]
public void QuitDriver()
{
driver.Quit();
}
[TestMethod]
public void BasicOptions()
{
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
[TestMethod]
public void InstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void UnInstallAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
Assert.AreEqual(driver.FindElements(By.Id("webextensions-selenium-example")).Count, 0);
}
[TestMethod]
public void InstallUnsignedAddon()
{
driver = new FirefoxDriver();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
IWebElement injected = driver.FindElement(By.Id("webextensions-selenium-example"));
Assert.AreEqual("Content injected by webextensions-selenium-example", injected.Text);
}
[TestMethod]
public void HeadlessOptions()
{
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
}
}
}
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
/examples/javascript/test/browser/firefoxSpecificFunctionalities.spec.js
const {Browser, By} = require('selenium-webdriver');
const Firefox = require('selenium-webdriver/firefox');
const options = new Firefox.Options();
const path = require('path');
const {suite} = require("selenium-webdriver/testing");
const assert = require("assert");
suite(function (env) {
describe('Should be able to Test Command line arguments', function () {
it('headless', async function () {
let driver = await env.builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
await driver.quit();
});
it('Should be able to add extension', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
it('Should be able to install unsigned addon', async function () {
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath, true);
await driver.uninstallAddon(id);
await driver.get('https://www.selenium.dev/selenium/web/blank.html');
const ele = await driver.findElements(By.id("webextensions-selenium-example"));
assert.equal(ele.length, 0);
await driver.quit();
});
});
}, { browsers: [Browser.FIREFOX]});
Full page screenshots
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
Context
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java
package dev.selenium.browsers;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FirefoxTest extends BaseTest {
public FirefoxDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
}
@Test
public void installAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = driver.findElement(By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void uninstallAddon() {
driver = new FirefoxDriver();
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
Assertions.assertEquals(driver.findElements(By.id("webextensions-selenium-example")).size(), 0);
}
@Test
public void installUnsignedAddonPath() {
driver = new FirefoxDriver();
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
driver.get("https://www.selenium.dev/selenium/web/blank.html");
WebElement injected = getLocatedElement(driver, By.id("webextensions-selenium-example"));
Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText());
}
@Test
public void headlessOptions() {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
driver = new FirefoxDriver(options);
}
}
/examples/python/tests/browsers/test_firefox.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
def test_basic_options():
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
def test_install_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
def test_uninstall_addon(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
assert len(driver.find_elements(By.ID, "webextensions-selenium-example")) == 0
def test_install_unsigned_addon_directory(firefox_driver):
driver = firefox_driver
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
driver.get("https://www.selenium.dev/selenium/web/blank.html")
injected = driver.find_element(By.ID, "webextensions-selenium-example")
assert injected.text == "Content injected by webextensions-selenium-example"
/examples/ruby/spec/browsers/firefox_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Firefox' do
let(:driver) { start_firefox }
it 'basic options' do
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
end
it 'installs addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
driver.install_addon(extension_file_path)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'uninstalls addon' do
extension_file_path = File.expand_path('../extensions/webextensions-selenium-example.xpi', __dir__)
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
driver.get 'https://www.selenium.dev/selenium/web/blank.html'
expect(driver.find_elements(id: 'webextensions-selenium-example')).to be_empty
end
it 'installs unsigned addon' do
extension_dir_path = File.expand_path('../extensions/webextensions-selenium-example/', __dir__)
driver.install_addon(extension_dir_path, true)
driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
injected = driver.find_element(id: 'webextensions-selenium-example')
expect(injected.text).to eq 'Content injected by webextensions-selenium-example'
end
it 'add arguments' do
options = Selenium::WebDriver::Options.firefox(args: ['-headless'])
@driver = Selenium::WebDriver.for :firefox, options: options
@driver.get('https://www.google.com')
end
end
Note: As of Firefox 138, geckodriver needs to be started with the argument --allow-system-access
to switch the context to CHROME
.
4 - IE 特定功能
自2022年6月起, Selenium 正式不再支持独立的 Internet Explorer. Internet Explorer 驱动程序仍支持在 “IE 兼容模式” 下运行 Microsoft Edge.
特别注意事项
IE 驱动程序是 Selenium 项目直接维护的唯一驱动程序. 虽然 32 位和 64 位版本的版本的二进制文件, 但有一些64位驱动程序的 已知限制. 因此, 建议使用 32 位驱动程序.
有关使用 Internet Explorer 的其他信息, 请参见 IE 驱动程序服务器页面
选项
在 Internet Explorer 兼容模式下启动 Microsoft Edge 浏览器, 并使用基本定义的选项, 看起来就像这样:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
driver = webdriver.Ie(options=options)
driver.quit()
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
截至 Internet Explorer 驱动程序 v4.5.0:
- 如果系统中没有 IE(Windows 11 中的默认设置), 则无需使用上述两个参数. 使用上述两个参数.IE 驱动程序将使用 Edge, 并自动对其进行定位.
- 如果系统上同时存在 IE 和 Edge, 则只需设置附加到 Edge、 IE 驱动程序将自动在系统中定位 Edge.
因此, 如果系统中没有 IE, 您只需要:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
<p><a href=/documentation/about/contributing/#moving-examples>
<span class="selenium-badge-code" data-bs-toggle="tooltip" data-bs-placement="right"
title="One or more of these examples need to be implemented in the examples directory; click for details in the contribution guide">Move Code</span></a></p>
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
以下是几种具有不同功能的常见用例:
fileUploadDialogTimeout
在某些环境中, 当打开文件上传对话框时, Internet Explorer可能会超时. IEDriver的默认超时为1000毫秒, 但您可以使用fileUploadDialogTimeout功能来增加超时时间.
InternetExplorerOptions options = new InternetExplorerOptions();
options.waitForUploadDialogUpTo(Duration.ofSeconds(2));
WebDriver driver = new RemoteWebDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.waitForUploadDialogUpTo(Duration.ofSeconds(2))
val driver = RemoteWebDriver(options)
ensureCleanSession
设置为 true
时,
此功能将清除InternetExplorer所有正在运行实例的
缓存, 浏览器历史记录和Cookies
(包括手动启动或由驱动程序启动的实例) .
默认情况下, 此设置为 false
.
使用此功能将导致启动浏览器时性能下降, 因为驱动程序将等待直到缓存清除后再启动IE浏览器.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.destructivelyEnsureCleanSession();
WebDriver driver = new RemoteWebDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.EnsureCleanSession = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ensureCleanSession(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.destructivelyEnsureCleanSession()
val driver = RemoteWebDriver(options)
ignoreZoomSetting
InternetExplorer驱动程序期望浏览器的缩放级别为100%, 否则驱动程序将可能抛出异常. 通过将 ignoreZoomSetting 设置为 true, 可以禁用此默认行为.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.ignoreZoomSettings();
WebDriver driver = new RemoteWebDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.IgnoreZoomLevel = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ignoreZoomSetting(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.ignoreZoomSettings()
val driver = RemoteWebDriver(options)
ignoreProtectedModeSettings
启动新的IE会话时是否跳过 保护模式 检查.
如果未设置, 并且所有区域的 保护模式 设置都不同, 则驱动程序将可能引发异常.
如果将功能设置为 true
,
则测试可能会变得不稳定, 无响应, 或者浏览器可能会挂起.
但是, 到目前为止,
这仍然是第二好的选择,
并且第一选择应该 始终 是手动实际设置每个区域的保护模式设置.
如果用户正在使用此属性,
则只会给予 “尽力而为” 的支持.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.introduceFlakinessByIgnoringSecurityDomains();
WebDriver driver = new RemoteWebDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().introduceFlakinessByIgnoringProtectedModeSettings(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.introduceFlakinessByIgnoringSecurityDomains()
val driver = RemoteWebDriver(options)
silent
设置为 true
时,
此功能将禁止IEDriverServer的诊断输出.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("silent", true);
WebDriver driver = new InternetExplorerDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalInternetExplorerOption("silent", true);
IWebDriver driver = new InternetExplorerDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const {Builder,By, Capabilities} = require('selenium-webdriver');
let caps = Capabilities.ie();
caps.set('silent', true);
(async function example() {
let driver = await new Builder()
.forBrowser('internet explorer')
.withCapabilities(caps)
.build();
try {
await driver.get('http://www.google.com/ncr');
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.setCapability("silent", true)
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
IE 命令行选项
Internet Explorer包含几个命令行选项, 使您可以进行故障排除和配置浏览器.
下面介绍了一些受支持的命令行选项
-private : 用于在私有浏览模式下启动IE. 这适用于IE 8和更高版本.
-k : 在kiosk模式下启动Internet Explorer. 浏览器在一个最大化的窗口中打开, 该窗口不显示地址栏, 导航按钮或状态栏.
-extoff : 在无附加模式下启动IE. 此选项专门用于解决浏览器加载项问题. 在IE 7和更高版本中均可使用.
注意: forceCreateProcessApi 应该启用命令行参数才能正常工作.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
options.addCommandSwitches("-k");
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
options.BrowserCommandLineArguments = "-k";
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.addBrowserCommandSwitches('-k');
options.addBrowserCommandSwitches('-private');
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
options.addCommandSwitches("-k")
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
forceCreateProcessApi
强制使用CreateProcess API启动Internet Explorer. 默认值为false.
对于IE 8及更高版本, 此选项要求将 “TabProcGrowth” 注册表值设置为0.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
服务
Service page 描述了所有浏览器通用的服务设置.
日志输出
获取驱动程序日志有助于调试各种问题. 服务类可让您指示日志的去向. 除非用户指定了日志输出的位置, 否则日志输出将被忽略.
文件输出
更改日志输出以保存到特定文件:
.withLogFile(getLogLocation())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting file output by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: String representing path to log file
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
控制台输出
要更改日志输出, 使其在控制台中显示为标准输出:
.withLogOutput(System.out)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting console output by System Property;
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
日志级别
有 6 种可用的日志级别:FATAL
、ERROR
、WARN
、INFO
、DEBUG
和 TRACE
如果指定了日志输出, 默认级别为FATAL
.
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting log level by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY
Property value: String representation of InternetExplorerDriverLogLevel.DEBUG.toString()
enum
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = Environment.GetEnvironmentVariable("EDGE_BINARY");
driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
辅助文件路径
.withExtractPath(getTempDirectory())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LibraryExtractionPath = GetTempDirectory();
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = Environment.GetEnvironmentVariable("EDGE_BINARY");
driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
5 - Safari 特定功能
与Chromium和Firefox驱动不同, safari驱动随操作系统安装. 要在 Safari 上启用自动化, 请从终端运行以下命令:
safaridriver --enable
选项
所有浏览器通用的Capabilities在选项页.
Safari独有的Capabilities可以在Apple的页面关于Safari的WebDriver 上找到
使用基本定义的选项启动 Safari 会话如下所示:
}
/examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
}
def test_basic_options():
options = SafariOptions()
/examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.safari.options import Options as SafariOptions
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/SafariTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Safari;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("OSX")]
public class SafariTest
{
[TestMethod]
public void BasicOptions()
{
var options = new SafariOptions();
var driver = new SafariDriver(options);
driver.Quit();
}
}
}
@driver = Selenium::WebDriver.for :safari, options: options
end
/examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
/examples/javascript/test/browser/safariSpecificCap.spec.js
const safari = require('selenium-webdriver/safari');
const {Browser} = require("selenium-webdriver");
const { suite } = require('selenium-webdriver/testing')
const options = new safari.Options();
const process = require('node:process');
suite(function(env) {
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.SAFARI]});
val options = SafariOptions()
val driver = SafariDriver(options)
移动端
那些希望在iOS上自动化Safari的人可以参考 Appium 项目.
服务
所有浏览器通用的服务设置在 服务页面.
日志
与其他浏览器不同,
Safari 浏览器不允许您选择日志的输出位置或更改级别.
一个可用选项是关闭或打开日志.
如果日志处于打开状态,
则可以在以下位置找到它们: ~/Library/Logs/com.apple.WebDriver/
.
.withLogging(true)
examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
}
注意: Java也允许使用环境变量进行设置;
属性键: SafariDriverService.SAFARI_DRIVER_LOGGING
属性值: "true"
或 "false"
service = webdriver.safari.service.Service(service_args=["--diagnose"])
examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.safari.options.Options()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.safari.service.Service(service_args=["--diagnose"])
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
service.args << '--diagnose'
examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enable logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end
Safari Technology Preview
Apple 提供了其浏览器的开发版本 — Safari Technology Preview
在代码中使用此版本:
examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
}
options = webdriver.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.safari.options.Options()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.safari.service.Service(service_args=["--diagnose"])
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enable logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end