Each browser has custom capabilities and unique features.
This is the multi-page printable view of this section. Click here to print.
Supported Browsers
- 1: Chrome specific functionality
- 2: Edge specific functionality
- 3: Firefox specific functionality
- 4: IE specific functionality
- 5: Safari specific functionality
1 - Chrome specific functionality
By default, Selenium 4 is compatible with Chrome v75 and greater. Note that the version of the Chrome browser and the version of chromedriver must match the major version.
Options
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Chrome and Chromium are documented at Google’s page for Capabilities & ChromeOptions
Starting a Chrome session with basic defined options looks like this:
}
/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]});
Arguments
The args
parameter is for a list of command line switches to be used when starting the browser.
There are two excellent resources for investigating these arguments:
Commonly used args include --start-maximized
, --headless=new
and --user-data-dir=...
Add an argument to options:
/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]});
Start browser in a specified location
The binary
parameter takes the path of an alternate location of browser to use. With this parameter you can
use chromedriver to drive various Chromium based browsers.
Add a browser location to options:
/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);
}
}
}
/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]});
Add extensions
The extensions
parameter accepts crx files. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
Add an extension to options:
/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]});
Keeping browser open
Setting the detach
parameter to true will keep the browser open after the process has ended,
so long as the quit command is not sent to the driver.
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]});
Excluding arguments
Chromedriver has several default arguments it uses to start the browser.
If you do not want those arguments added, pass them into excludeSwitches
.
A common example is to turn the popup blocker back on. A full list of default arguments
can be parsed from the
Chromium Source Code
Set excluded arguments on options:
/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
Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.
Log output
Getting driver logs can be helpful for debugging 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:
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;
}
}
Note: Java also allows setting file output by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
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;
}
}
}
args = ["--log-path=#{file_name}", '--verbose']
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
Console output
To change the logging output to display in the console as STDOUT:
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class ChromeTest {
private ChromeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
}
@Test
public void arguments() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
@Test
public void excludeSwitches() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new ChromeDriver(options);
}
@Test
public void logsToFile() throws IOException {
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
ChromeDriverService service = new ChromeDriverService.Builder()
.withLogLevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
ChromeDriverService service = new ChromeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
ChromeDriverService service = new ChromeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new ChromeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("chromedriver-", ".log");
}
return logLocation;
}
}
Note: Java also allows setting console output by System Property;
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or 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
end
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
Log level
There are 6 available log levels: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, and OFF
.
Note that --verbose
is equivalent to --log-level=ALL
and --silent
is equivalent to --log-level=OFF
,
so this example is just setting the log level generically:
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;
}
}
Note: Java also allows setting log level by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of ChromiumDriverLogLevel
enum
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()
end
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
Log file features
There are 2 features that are only available when logging to a file:
- append log
- readable timestamps
To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.
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;
}
}
Note: Java also allows toggling these features by System Property:
Property keys: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY
and ChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
Property value: "true"
or "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
Disabling build check
Chromedriver and Chrome browser versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Chrome. Note that this is an unsupported feature, and bugs will not be investigated.
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;
}
}
Note: Java also allows disabling build checks by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
Property value: "true"
or "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
Special Features
Some browsers have implemented additional features that are unique to them.
Casting
You can drive Chrome Cast devices, including sharing tabs
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
Network conditions
You can simulate various network conditions.
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
Logs
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
Permissions
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
See the Chrome DevTools section for more information about using Chrome DevTools
2 - Edge specific functionality
Microsoft Edge is implemented with Chromium, with the earliest supported version of v79. Similar to Chrome, the major version number of edgedriver must match the major version of the Edge browser.
Options
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Chromium are documented at Google’s page for Capabilities & ChromeOptions
Starting an Edge session with basic defined options looks like this:
/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]});
Arguments
The args
parameter is for a list of command line switches to be used when starting the browser.
There are two excellent resources for investigating these arguments:
Commonly used args include --start-maximized
, --headless=new
and --user-data-dir=...
Add an argument to 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]});
Start browser in a specified location
The binary
parameter takes the path of an alternate location of browser to use. With this parameter you can
use chromedriver to drive various Chromium based browsers.
Add a browser location to 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
Add extensions
The extensions
parameter accepts crx files. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
Add an extension to 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]});
Keeping browser open
Setting the detach
parameter to true will keep the browser open after the process has ended,
so long as the quit command is not sent to the 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]});
Excluding arguments
MSEdgedriver has several default arguments it uses to start the browser.
If you do not want those arguments added, pass them into excludeSwitches
.
A common example is to turn the popup blocker back on. A full list of default arguments
can be parsed from the
Chromium Source Code
Set excluded arguments on 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]});
Service
Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.
Log output
Getting driver logs can be helpful for debugging 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:
.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;
}
}
Note: Java also allows setting file output by System Property:
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
Console output
To change the logging output to display in the console as STDOUT:
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
Note: Java also allows setting console output by System Property;
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or 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
Log level
There are 6 available log levels: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, and OFF
.
Note that --verbose
is equivalent to --log-level=ALL
and --silent
is equivalent to --log-level=OFF
,
so this example is just setting the log level generically:
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;
}
}
Note: Java also allows setting log level by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
Property value: 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
Log file features
There are 2 features that are only available when logging to a file:
- append log
- readable timestamps
To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.
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;
}
}
Note: Java also allows toggling these features by System Property:
Property keys: EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY
and EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
Property value: "true"
or "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
Disabling build check
Edge browser and msedgedriver versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Edge. Note that this is an unsupported feature, and bugs will not be investigated.
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;
}
}
Note: Java also allows disabling build checks by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
Property value: "true"
or "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 Mode
Microsoft Edge can be driven in “Internet Explorer Compatibility Mode”, which uses the Internet Explorer Driver classes in conjunction with Microsoft Edge. Read the Internet Explorer page for more details.
Special Features
Some browsers have implemented additional features that are unique to them.
Casting
You can drive Chrome Cast devices with Edge, including sharing tabs
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
Network conditions
You can simulate various network conditions.
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
Logs
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
Permissions
examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java
package dev.selenium.browsers;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chromium.ChromiumDriverLogLevel;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class EdgeTest {
private EdgeDriver driver;
private File logLocation;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
driver.quit();
}
@Test
public void basicOptions() {
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
}
@Test
public void arguments() {
EdgeOptions options = new EdgeOptions();
options.addArguments("--start-maximized");
driver = new EdgeDriver(options);
}
@Test
public void excludeSwitches() {
EdgeOptions options = new EdgeOptions();
options.setExperimentalOption("excludeSwitches", ImmutableList.of("disable-popup-blocking"));
driver = new EdgeDriver(options);
}
@Test
public void logsToFile() throws IOException {
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
EdgeDriverService service = new EdgeDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
EdgeDriverService service = new EdgeDriverService.Builder()
.withLoglevel(ChromiumDriverLogLevel.DEBUG)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("[DEBUG]:"));
}
@Test
public void configureDriverLogs() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.DEBUG.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withAppendLog(true)
.withReadableTimestamp(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Pattern pattern = Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d", Pattern.CASE_INSENSITIVE);
Assertions.assertTrue(pattern.matcher(fileContent).find());
}
@Test
public void disableBuildChecks() throws IOException {
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,
getLogLocation().getAbsolutePath());
System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,
ChromiumDriverLogLevel.WARNING.toString());
EdgeDriverService service = new EdgeDriverService.Builder()
.withBuildCheckDisabled(true)
.build();
driver = new EdgeDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
String expected = "[WARNING]: You are using an unsupported command-line switch: --disable-build-check";
Assertions.assertTrue(fileContent.contains(expected));
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("msedgedriver-", ".log");
}
return logLocation;
}
}
/examples/python/tests/browsers/test_edge.py
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions
def test_basic_options():
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
def test_headless():
options = EdgeOptions()
options.add_argument("--headless=new")
driver = webdriver.Edge(options=options)
driver.get('http://selenium.dev')
driver.quit()
/examples/ruby/spec/browsers/edge_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Edge' do
let(:driver) { start_session }
it 'basic options' do
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
end
it 'add arguments' do
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
@driver.get('https://www.google.com')
end
end
DevTools
See the Chrome DevTools section for more information about using DevTools in Edge
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]});
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 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
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 = FirefoxDriver(options)
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
Some browsers have implemented additional features that are unique to them.
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 specific functionality
As of June 2022, Selenium officially no longer supports standalone Internet Explorer. The Internet Explorer driver still supports running Microsoft Edge in “IE Compatibility Mode.”
Special considerations
The IE Driver is the only driver maintained by the Selenium Project directly. While binaries for both the 32-bit and 64-bit versions of Internet Explorer are available, there are some known limitations with the 64-bit driver. As such it is recommended to use the 32-bit driver.
Additional information about using Internet Explorer can be found on the IE Driver Server page
Options
Starting a Microsoft Edge browser in Internet Explorer Compatibility mode with basic defined options looks like this:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
driver = webdriver.Ie(options=options)
driver.quit()
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
As of Internet Explorer Driver v4.5.0:
- If IE is not present on the system (default in Windows 11), you do not need to use the two parameters above. IE Driver will use Edge and will automatically locate it.
- If IE and Edge are both present on the system, you only need to set attaching to Edge, IE Driver will automatically locate Edge on your system.
So, if IE is not on the system, you only need:
/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
[TestMethod]
public void BasicOptions()
{
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
Here are a few common use cases with different capabilities:
fileUploadDialogTimeout
In some environments, Internet Explorer may timeout when opening the File Upload dialog. IEDriver has a default timeout of 1000ms, but you can increase the timeout using the fileUploadDialogTimeout capability.
InternetExplorerOptions options = new InternetExplorerOptions();
options.waitForUploadDialogUpTo(Duration.ofSeconds(2));
WebDriver driver = new RemoteWebDriver(options);
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.waitForUploadDialogUpTo(Duration.ofSeconds(2))
val driver = RemoteWebDriver(options)
ensureCleanSession
When set to true
, this capability clears the Cache,
Browser History and Cookies for all running instances
of InternetExplorer including those started manually
or by the driver. By default, it is set to false
.
Using this capability will cause performance drop while launching the browser, as the driver will wait until the cache gets cleared before launching the IE browser.
This capability accepts a Boolean value as parameter.
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 driver expects the browser zoom level to be 100%, else the driver will throw an exception. This default behaviour can be disabled by setting the ignoreZoomSetting to true.
This capability accepts a Boolean value as parameter.
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
Whether to skip the Protected Mode check while launching a new IE session.
If not set and Protected Mode settings are not same for all zones, an exception will be thrown by the driver.
If capability is set to true
, tests may
become flaky, unresponsive, or browsers may hang.
However, this is still by far a second-best choice,
and the first choice should always be to actually
set the Protected Mode settings of each zone manually.
If a user is using this property,
only a “best effort” at support will be given.
This capability accepts a Boolean value as parameter.
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
When set to true
, this capability suppresses the
diagnostic output of the IEDriverServer.
This capability accepts a Boolean value as parameter.
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()
}
}
Command-Line Options
Internet Explorer includes several command-line options that enable you to troubleshoot and configure the browser.
The following describes few supported command-line options
-private : Used to start IE in private browsing mode. This works for IE 8 and later versions.
-k : Starts Internet Explorer in kiosk mode. The browser opens in a maximized window that does not display the address bar, the navigation buttons, or the status bar.
-extoff : Starts IE in no add-on mode. This option specifically used to troubleshoot problems with browser add-ons. Works in IE 7 and later versions.
Note: forceCreateProcessApi should to enabled in-order for command line arguments to work.
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
Forces launching Internet Explorer using the CreateProcess API. The default value is false.
For IE 8 and above, this option requires the “TabProcGrowth” registry value to be set to 0.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
/examples/python/tests/browsers/test_internet_explorer.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.ie.options import Options as InternetExplorerOptions
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options():
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
/examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
it 'basic options' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
.withLogFile(getLogLocation())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting file output by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: String representing path to log file
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Console output
To change the logging output to display in the console as STDOUT:
.withLogOutput(System.out)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting console output by System Property;
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Log Level
There are 6 available log levels: FATAL
, ERROR
, WARN
, INFO
, DEBUG
, and TRACE
If logging output is specified, the default level is FATAL
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
Note: Java also allows setting log level by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY
Property value: String representation of InternetExplorerDriverLogLevel.DEBUG.toString()
enum
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = Environment.GetEnvironmentVariable("EDGE_BINARY");
driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
Supporting Files Path
.withExtractPath(getTempDirectory())
examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.ie.InternetExplorerOptions;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@EnabledOnOs(OS.WINDOWS)
public class InternetExplorerTest {
public InternetExplorerDriver driver;
private File logLocation;
private File tempDirectory;
@AfterEach
public void quit() {
if (logLocation != null && logLocation.exists()) {
logLocation.delete();
}
if (tempDirectory != null && tempDirectory.exists()) {
tempDirectory.delete();
}
driver.quit();
}
@Test
public void basicOptionsWin10() {
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(System.getProperty("webdriver.edge.binary"));
driver = new InternetExplorerDriver(options);
}
@Test
public void basicOptionsWin11() {
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
@Test
public void logsToFile() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogFile(getLogLocation())
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsToConsole() throws IOException {
System.setOut(new PrintStream(getLogLocation()));
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogOutput(System.out)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));
}
@Test
public void logsWithLevel() throws IOException {
System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,
getLogLocation().getAbsolutePath());
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
.build();
driver = new InternetExplorerDriver(service);
String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));
Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));
}
@Test
public void supportingFilesLocation() throws IOException {
InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.withExtractPath(getTempDirectory())
.build();
driver = new InternetExplorerDriver(service);
Assertions.assertTrue(new File(getTempDirectory() + "/IEDriver.tmp").exists());
}
private File getLogLocation() throws IOException {
if (logLocation == null || !logLocation.exists()) {
logLocation = File.createTempFile("iedriver-", ".log");
}
return logLocation;
}
private File getTempDirectory() throws IOException {
if (tempDirectory == null || !tempDirectory.exists()) {
tempDirectory = Files.createTempDirectory("supporting-").toFile();
}
return tempDirectory;
}
}
examples/python/tests/browsers/test_internet_explorer.py
import os
import subprocess
import sys
import pytest
from selenium import webdriver
EDGE_BINARY = os.getenv("EDGE_BINARY")
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win10():
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = EDGE_BINARY
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_basic_options_win11():
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_to_file(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='INFO')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert "Starting WebDriver server" in fp.readline()
driver.quit()
@pytest.mark.skip(reason="this is not supported, yet")
def test_log_to_stdout(capfd):
service = webdriver.ie.service.Service(log_output=subprocess.STDOUT)
driver = webdriver.Ie(service=service)
out, err = capfd.readouterr()
assert "Started InternetExplorerDriver server" in out
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_log_level(log_path):
service = webdriver.ie.service.Service(log_file=log_path, log_level='WARN')
driver = webdriver.Ie(service=service)
with open(log_path, 'r') as fp:
assert 'Invalid capability setting: timeouts is type null' in fp.readline()
driver.quit()
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_supporting_files(temp_dir):
service = webdriver.ie.service.Service(service_args=["–extract-path="+temp_dir])
driver = webdriver.Ie(service=service)
driver.quit()
service.LibraryExtractionPath = GetTempDirectory();
examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.IE;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("WINDOWS")]
public class InternetExplorerTest
{
private InternetExplorerDriver driver;
private string _logLocation;
private string _tempPath;
[TestCleanup]
public void Cleanup()
{
if (_logLocation != null && File.Exists(_logLocation))
{
File.Delete(_logLocation);
}
if (_tempPath != null && File.Exists(_tempPath))
{
File.Delete(_tempPath);
}
driver.Quit();
}
[TestMethod]
public void BasicOptionsWin10()
{
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = Environment.GetEnvironmentVariable("EDGE_BINARY");
driver = new InternetExplorerDriver(options);
}
[TestMethod]
public void BasicOptionsWin11()
{
var options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToFile()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("geckodriver INFO Listening on")));
}
[TestMethod]
[Ignore("Not implemented")]
public void LogsToConsole()
{
var stringWriter = new StringWriter();
var originalOutput = Console.Out;
Console.SetOut(stringWriter);
var service = InternetExplorerDriverService.CreateDefaultService();
//service.LogToConsole = true;
driver = new InternetExplorerDriver(service);
Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));
Console.SetOut(originalOutput);
stringWriter.Dispose();
}
[TestMethod]
public void LogsLevel()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LogFile = GetLogLocation();
service.LoggingLevel = InternetExplorerDriverLogLevel.Warn;
driver = new InternetExplorerDriver(service);
driver.Quit(); // Close the Service log file before reading
var lines = File.ReadLines(GetLogLocation());
Assert.IsNotNull(lines.FirstOrDefault(line => line.Contains("Invalid capability setting: timeouts is type null")));
}
[TestMethod]
public void SupportingFilesLocation()
{
var service = InternetExplorerDriverService.CreateDefaultService();
service.LibraryExtractionPath = GetTempDirectory();
driver = new InternetExplorerDriver(service);
Assert.IsTrue(File.Exists(GetTempDirectory() + "/IEDriver.tmp"));
}
private string GetLogLocation()
{
if (_logLocation == null || !File.Exists(_logLocation))
{
_logLocation = Path.GetTempFileName();
}
return _logLocation;
}
private string GetTempDirectory()
{
if (_tempPath == null || !File.Exists(_tempPath))
{
_tempPath = Path.GetTempPath();
}
return _tempPath;
}
}
}
examples/ruby/spec/browsers/internet_explorer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Internet Explorer', exclusive: {platform: :windows} do
describe 'Options' do
it 'basic options Win10' do
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = ENV.fetch('EDGE_BINARY', nil)
@driver = Selenium::WebDriver.for :ie, options: options
end
it 'basic options Win11' do
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
end
end
describe 'Service' do
let(:file_name) { Tempfile.new('iedriver').path }
let(:root_directory) { Dir.mktmpdir }
after do
FileUtils.rm_f(file_name)
FileUtils.remove_entry root_directory
end
it 'logs to file' do
service = Selenium::WebDriver::Service.ie
service.log = file_name
@driver = Selenium::WebDriver.for :ie, service: service
expect(File.readlines(file_name).first).to include('Started InternetExplorerDriver server')
end
it 'logs to console' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Started InternetExplorerDriver server/).to_stdout_from_any_process
end
it 'sets log level' do
service = Selenium::WebDriver::Service.ie
service.log = $stdout
service.args << '-log-level=WARN'
expect {
@driver = Selenium::WebDriver.for :ie, service: service
}.to output(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_process
end
it 'sets location for supporting files' do
service = Selenium::WebDriver::Service.ie
service.args << "–extract-path=#{root_directory}"
@driver = Selenium::WebDriver.for :ie, service: service
end
end
end
5 - Safari specific functionality
Unlike Chromium and Firefox drivers, the safaridriver is installed with the Operating System. To enable automation on Safari, run the following command from the terminal:
safaridriver --enable
Options
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Safari can be found at Apple’s page About WebDriver for Safari
Starting a Safari session with basic defined options looks like this:
}
/examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
driver.quit();
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
}
def test_basic_options():
options = SafariOptions()
/examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.safari.options import Options as SafariOptions
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = SafariOptions()
driver = webdriver.Safari(options=options)
driver.quit()
/examples/dotnet/SeleniumDocs/Browsers/SafariTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Safari;
using SeleniumDocs.TestSupport;
namespace SeleniumDocs.Browsers
{
[TestClassCustom]
[EnabledOnOs("OSX")]
public class SafariTest
{
[TestMethod]
public void BasicOptions()
{
var options = new SafariOptions();
var driver = new SafariDriver(options);
driver.Quit();
}
}
}
@driver = Selenium::WebDriver.for :safari, options: options
end
/examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
/examples/javascript/test/browser/safariSpecificCap.spec.js
const safari = require('selenium-webdriver/safari');
const {Browser} = require("selenium-webdriver");
const { suite } = require('selenium-webdriver/testing')
const options = new safari.Options();
const process = require('node:process');
suite(function(env) {
describe('Should be able to Test Command line arguments', function () {
(process.platform === 'darwin' ? it : it.skip)('headless', async function () {
let driver = await env.builder()
.setSafariOptions(options)
.build();
await driver.get('https://www.google.com');
await driver.quit();
});
});
}, { browsers: [Browser.SAFARI]});
val options = SafariOptions()
val driver = SafariDriver(options)
Mobile
Those looking to automate Safari on iOS should look to the Appium project.
Service
Service settings common to all browsers are described on the Service page.
Logging
Unlike other browsers, Safari doesn’t let you choose where logs are output, or change levels. The one option
available is to turn logs off or on. If logs are toggled on, they can be found at:~/Library/Logs/com.apple.WebDriver/
.
.withLogging(true)
examples/java/src/test/java/dev/selenium/browsers/SafariTest.java
package dev.selenium.browsers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariDriverService;
import org.openqa.selenium.safari.SafariOptions;
@EnabledOnOs(OS.MAC)
public class SafariTest {
public SafariDriver driver;
@AfterEach
public void quit() {
if (driver != null) {
driver.quit();
}
}
@Test
public void basicOptions() {
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
}
@Test
public void enableLogs() {
SafariDriverService service = new SafariDriverService.Builder()
.withLogging(true)
.build();
driver = new SafariDriver(service);
}
}
Note: Java also allows setting console output by System Property;
Property key: SafariDriverService.SAFARI_DRIVER_LOGGING
Property value: "true"
or "false"
service = webdriver.safari.service.Service(service_args=["--diagnose"])
examples/python/tests/browsers/test_safari.py
import sys
import pytest
from selenium import webdriver
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_basic_options():
options = webdriver.safari.options.Options()
driver = webdriver.Safari(options=options)
driver.quit()
@pytest.mark.skipif(sys.platform != "darwin", reason="requires Mac")
def test_enable_logging():
service = webdriver.safari.service.Service(service_args=["--diagnose"])
driver = webdriver.Safari(service=service)
driver.quit()
@pytest.mark.skip(reason="Not installed on Mac GitHub Actions Runner Image")
def test_technology_preview():
options = webdriver.safari.options.Options()
options.use_technology_preview = True
service = webdriver.safari.service.Service(
executable_path='/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
)
driver = webdriver.Safari(options=options, service=service)
driver.quit()
service.args << '--diagnose'
examples/ruby/spec/browsers/safari_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Safari', exclusive: {platform: :macosx} do
describe 'Options' do
it 'basic options' do
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
end
end
describe 'Service' do
let(:directory) { "#{Dir.home}/Library/Logs/com.apple.WebDriver/*" }
it 'enable logs' do
original_count = Dir[directory].length
service = Selenium::WebDriver::Service.safari
service.args << '--diagnose'
@driver = Selenium::WebDriver.for :safari, service: service
expect(Dir[directory].length - original_count).to eq 1
end
it 'does not set log output' do
service = Selenium::WebDriver::Service.safari
expect {
service.log = $stdout
}.to raise_error(Selenium::WebDriver::Error::WebDriverError, /Safari Service does not support setting log output/)
end
end
end
Safari Technology Preview
Apple provides a development version of their browser — Safari Technology Preview
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