Este é um exemplo de como iniciar uma sessão Chrome com um conjunto de opções básicas:
3639
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L9-L10" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
2932
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
Alguns exemplos de uso com capacidades diferentes:
Argumentos
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:
4446
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L18" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
3840
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L29" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
4850
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
The extensions parameter accepts crx files. As for unpacked directories,
please use the load-extension argument instead, as mentioned in
this post.
Adicionar uma extensão:
6466
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L40" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
6062
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L51" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: This is already the default behavior in .NET.
4446
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
Chrome adiciona vários parametros, se não os pretende adicionar, passe-os em excludeSwitches.
Um exemplo comum é voltar a activar o bloqueador de popups.
A full list of default arguments
can be parsed from the
Chromium Source Code
Exclua parametros:
7779
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("–start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['–log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['–disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_chrome.py#L62" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
7577
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options();describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});xit('Start browser from specified location ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Basic Chrome test',asyncfunction(){constOptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){constoptions=newChrome.Options();letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("–start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java#L100-L101" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("–start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java#L114-L115" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
require'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'–start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',dir)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'–log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/[DEBUG]:/).any?).toeqtrueendit'sets log features'doargs=["–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:serviceexpect(File.readlines(file_name).grep(/[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['–verbose']service.args<<'–disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/[WARNING]: You are using an unsupported command-line switch: –disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'</span>
'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/spec/browsers/chrome_spec.rb#L76" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("–start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java#L129-L130" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("–start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java#L147-L148" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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"
103105
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("–start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/ChromeTest.java#L166-L167" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: Java also allows disabling build checks by System Property: Property key: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK Property value: "true" or "false"
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassChromeTest{privateChromeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newChromeOptions();driver=newChromeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newChromeOptions();options.AddArgument("--start-maximized");driver=newChromeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newChromeOptions();options.BinaryLocation=GetChromeLocation();driver=newChromeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newChromeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newChromeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newChromeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newChromeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting ChromeDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=ChromeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newChromeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting ChromeDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=ChromeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newChromeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetChromeLocation(){varoptions=newChromeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
Pode comandar dispositivos Chrome Cast, incluindo partilhar abas
229236
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
Pode simular vários estados de rede (como exemplo, simular situações com pouca banda).
The following examples are for local webdrivers. For remote webdrivers,
please refer to the
Remote WebDriver page.
203211
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeDriverService;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassChromeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY);System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newChromeDriver(options);}@Testpublicvoidarguments(){ChromeOptionsoptions=getDefaultChromeOptions();options.addArguments("--start-maximized");driver=newChromeDriver(options);}@TestpublicvoidsetBrowserLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBinary(getChromeLocation());driver=newChromeDriver(options);}@TestpublicvoidextensionOptions(){ChromeOptionsoptions=getDefaultChromeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newChromeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){ChromeOptionsoptions=getDefaultChromeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newChromeDriver(options);}@TestpublicvoidloggingPreferences(){ChromeOptionsoptions=getDefaultChromeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(ChromeOptions.LOGGING_PREFS,logPrefs);driver=newChromeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");ChromeDriverServiceservice=newChromeDriverService.Builder().withLogFile(logLocation).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));ChromeDriverServiceservice=newChromeDriverService.Builder().withLogOutput(System.out).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting ChromeDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());ChromeDriverServiceservice=newChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());ChromeDriverServiceservice=newChromeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newChromeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetChromeLocation(){ChromeOptionsoptions=getDefaultChromeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(ChromeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermission(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newChromeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((ChromeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((ChromeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((ChromeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){ChromeDriverdriver=newChromeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){ChromeDriverdriver=newChromeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_chrome_options()driver=webdriver.Chrome(options=options)driver.quit()deftest_args():options=get_default_chrome_options()options.add_argument("--start-maximized")driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(chrome_bin):options=get_default_chrome_options()options.binary_location=chrome_bindriver=webdriver.Chrome(options=options)driver.quit()deftest_add_extension():options=get_default_chrome_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_chrome_options()options.add_experimental_option("detach",True)driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_chrome_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Chrome(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.ChromeService(log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asfp:assert"Starting ChromeDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.ChromeService(log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert"Starting ChromeDriver"inoutdriver.quit()deftest_log_level(capfd):service=webdriver.ChromeService(service_args=['--log-level=DEBUG'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)out,err=capfd.readouterr()assert'[DEBUG]'inerrdriver.quit()deftest_log_features(log_path):service=webdriver.ChromeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Chrome(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(capfd):service=webdriver.ChromeService(service_args=['--disable-build-check'],log_output=subprocess.STDOUT)driver=webdriver.Chrome(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"out,err=capfd.readouterr()assertexpectedinerrdriver.quit()deftest_set_network_conditions():driver=webdriver.Chrome()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Chrome()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Chrome()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Chrome()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.chrome@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.chromeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:chrome,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.chromeoptions.binary=chrome_location@driver=Selenium::WebDriver.for:chrome,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.chromeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:chrome,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.chromeoptions.detach=true@driver=Selenium::WebDriver.for:chrome,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.chromeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:chrome,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('chromedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.chromeservice.log=file_name@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting ChromeDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.chromeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:chrome,service:service}.tooutput(/Starting ChromeDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.chromeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:chrome,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.chromelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:chrome,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:chromesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:chrome@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:chrome@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.chrome(browser_version:'stable')service=Selenium::WebDriver::Service.chromefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['CHROMEDRIVER_BIN']=finder.driver_pathENV['CHROME_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
Veja a secção [Chrome DevTools] para mais informação em como usar Chrome DevTools
2 - Funcionalidade específica do Edge
Estas capacidades e características são específicas ao navegador Microsoft Edge.
Microsoft Edge foi criado com recurso ao Chromium, cuja versão mais antiga suportada é a v79.
Tal como o Chrome, a versão (maior) do edgedriver deve ser igual à do navegador Edge.
Todas as capacidades e opções encontradas na página Chrome page irão funcionar de igual forma para o Edge.
Opções
Capabilities common to all browsers are described on the Options page.
Este é um exemplo de como iniciar uma sessão Edge com um conjunto de opções básicas:
3740
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L9-L10" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
2932
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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:
Opções mais frequentes incluem --start-maximized e --headless=new e --user-data-dir=...
Adicione uma opção:
4547
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L18" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
3840
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
5355
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L29" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
4850
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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:
6567
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L40" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
6062
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L51" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: This is already the default behavior in .NET.
4446
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
7880
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("–start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['–log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['–append-log','–readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['–disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":20001024/8,# 2000 kbps"upload_throughput":20001024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("–no-sandbox")returnoptions
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_edge.py#L62" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
7577
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
const{Browser,By,Builder}=require('selenium-webdriver');constedge=require('selenium-webdriver/edge');constoptions=newedge.Options();constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addArguments('--headless=new')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('exclude switches',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.excludeSwitches('enable-automation')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Keep browser open - set detach to true ',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.detachDriver(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');// As tests runs in ci, quitting the driver instance to avoid any failures
awaitdriver.quit();});it('Basic edge test',asyncfunction(){constOptions=newedge.Options();letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(Options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Add Extension',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.EDGE).setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx'])).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');letinjected=awaitdriver.findElement(By.id('webextensions-selenium-example'));assert.equal(awaitinjected.getText(),`Content injected by webextensions-selenium-example`)awaitdriver.quit();});});
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L101" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
7072
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L114" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
require'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'–start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',dir)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'–log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/[DEBUG]:/).any?).toeqtrueendit'sets log features'doargs=["–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:serviceexpect(File.readlines(file_name).grep(/[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['–verbose']service.args<<'–disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/[WARNING]: You are using an unsupported command-line switch: –disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'</span>
'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/ruby/spec/browsers/edge_spec.rb#L76" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L127-L128" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
9294
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L143-L144" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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"
103105
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
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.
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("–start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\[\d\d-\d\d-\d\d\d\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: –disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(20001024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/EdgeTest.java#L161-L162" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: Java also allows disabling build checks by System Property: Property key: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK Property value: "true" or "false"
114116
Show full example
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Text.RegularExpressions;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Edge;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassEdgeTest{privateEdgeDriverdriver;privatestring_logLocation; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newEdgeOptions();driver=newEdgeDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newEdgeOptions();options.AddArgument("--start-maximized");driver=newEdgeDriver(options);} [TestMethod]publicvoidSetBrowserLocation(){varoptions=newEdgeOptions();options.BinaryLocation=GetEdgeLocation();driver=newEdgeDriver(options);} [TestMethod]publicvoidInstallExtension(){varoptions=newEdgeOptions();varbaseDir=AppDomain.CurrentDomain.BaseDirectory;varextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.crx");options.AddExtension(extensionFilePath);driver=newEdgeDriver(options);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidExcludeSwitch(){varoptions=newEdgeOptions();options.AddExcludedArgument("disable-popup-blocking");driver=newEdgeDriver(options);} [TestMethod]publicvoidLogsToFile(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Starting Microsoft Edge WebDriver")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=EdgeDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newEdgeDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("Starting Microsoft Edge WebDriver"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("Not implemented")]publicvoidLogsLevel(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();// service.LogLevel = ChromiumDriverLogLevel.Debug driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("[DEBUG]:")));} [TestMethod] [Ignore("Not implemented")]publicvoidConfigureDriverLogs(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.EnableAppendLog=true;// service.readableTimeStamp = true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());varregex=newRegex(@"\[\d\d-\d\d-\d\d\d\d");Assert.IsNotNull(lines.FirstOrDefault(line=>regex.Matches("").Count>0));} [TestMethod]publicvoidDisableBuildCheck(){varservice=EdgeDriverService.CreateDefaultService();service.LogPath=GetLogLocation();service.EnableVerboseLogging=true;service.DisableBuildCheck=true;driver=newEdgeDriver(service);driver.Quit();// Close the Service log file before readingvarexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains(expected)));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestaticstringGetEdgeLocation(){varoptions=newEdgeOptions{BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
O Microsoft Edge pode ser controlado em modo “compatibilidade Internet Explorer”, são usadas
classes do Internet Explorer Driver em conjunção com o Microsoft Edge.
Leia a página Internet Explorer para mais detalhes.
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
224231
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importjava.util.List;importjava.util.Map;importjava.util.logging.Level;importjava.util.regex.Pattern;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chromium.ChromiumDriverLogLevel;importorg.openqa.selenium.chromium.ChromiumNetworkConditions;importorg.openqa.selenium.edge.EdgeDriver;importorg.openqa.selenium.edge.EdgeDriverService;importorg.openqa.selenium.edge.EdgeOptions;importorg.openqa.selenium.logging.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassEdgeTestextendsBaseTest{@AfterEachpublicvoidclearProperties(){System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY);System.clearProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY);}@TestpublicvoidbasicOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();driver=newEdgeDriver(options);}@Testpublicvoidarguments(){EdgeOptionsoptions=getDefaultEdgeOptions();options.addArguments("--start-maximized");driver=newEdgeDriver(options);}@TestpublicvoidsetBrowserLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBinary(getEdgeLocation());driver=newEdgeDriver(options);}@TestpublicvoidextensionOptions(){EdgeOptionsoptions=getDefaultEdgeOptions();Pathpath=Paths.get("src/test/resources/extensions/webextensions-selenium-example.crx");FileextensionFilePath=newFile(path.toUri());options.addExtensions(extensionFilePath);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoidexcludeSwitches(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setExperimentalOption("excludeSwitches",List.of("disable-popup-blocking"));driver=newEdgeDriver(options);}@TestpublicvoidloggingPreferences(){EdgeOptionsoptions=getDefaultEdgeOptions();LoggingPreferenceslogPrefs=newLoggingPreferences();logPrefs.enable(LogType.PERFORMANCE,Level.ALL);options.setCapability(EdgeOptions.LOGGING_PREFS,logPrefs);driver=newEdgeDriver(options);driver.get("https://www.selenium.dev");LogEntrieslogEntries=driver.manage().logs().get(LogType.PERFORMANCE);Assertions.assertFalse(logEntries.getAll().isEmpty());}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogFile(logLocation).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));EdgeDriverServiceservice=newEdgeDriverService.Builder().withLogOutput(System.out).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Starting Microsoft Edge WebDriver"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());EdgeDriverServiceservice=newEdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("[DEBUG]:"));}@TestpublicvoidconfigureDriverLogs()throwsIOException{FilelogLocation=getTempFile("configureDriverLogs",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.DEBUG.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Patternpattern=Pattern.compile("\\[\\d\\d-\\d\\d-\\d\\d\\d\\d",Pattern.CASE_INSENSITIVE);Assertions.assertTrue(pattern.matcher(fileContent).find());}@TestpublicvoiddisableBuildChecks()throwsIOException{FilelogLocation=getTempFile("disableBuildChecks",".log");System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY,ChromiumDriverLogLevel.WARNING.toString());EdgeDriverServiceservice=newEdgeDriverService.Builder().withBuildCheckDisabled(true).build();driver=newEdgeDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Stringexpected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check";Assertions.assertTrue(fileContent.contains(expected));}privateFilegetEdgeLocation(){EdgeOptionsoptions=getDefaultEdgeOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(EdgeDriverService.createDefaultService(),options);returnnewFile(finder.getBrowserPath());}@TestpublicvoidsetPermissions(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev");driver.setPermission("camera","denied");// Verify the permission state is 'denied'Stringscript="return navigator.permissions.query({ name: 'camera' })"+" .then(permissionStatus => permissionStatus.state);";StringpermissionState=(String)driver.executeScript(script);Assertions.assertEquals("denied",permissionState);driver.quit();}@TestpublicvoidsetNetworkConditions(){driver=newEdgeDriver();ChromiumNetworkConditionsnetworkConditions=newChromiumNetworkConditions();networkConditions.setOffline(false);networkConditions.setLatency(java.time.Duration.ofMillis(20));// 20 ms of latencynetworkConditions.setDownloadThroughput(2000*1024/8);// 2000 kbpsnetworkConditions.setUploadThroughput(2000*1024/8);// 2000 kbps((EdgeDriver)driver).setNetworkConditions(networkConditions);driver.get("https://www.selenium.dev");// Assert the network conditions are set as expectedChromiumNetworkConditionsactualConditions=((EdgeDriver)driver).getNetworkConditions();Assertions.assertAll(()->Assertions.assertEquals(networkConditions.getOffline(),actualConditions.getOffline()),()->Assertions.assertEquals(networkConditions.getLatency(),actualConditions.getLatency()),()->Assertions.assertEquals(networkConditions.getDownloadThroughput(),actualConditions.getDownloadThroughput()),()->Assertions.assertEquals(networkConditions.getUploadThroughput(),actualConditions.getUploadThroughput()));((EdgeDriver)driver).deleteNetworkConditions();driver.quit();}@TestpublicvoidcastFeatures(){EdgeDriverdriver=newEdgeDriver();List<Map<String,String>>sinks=driver.getCastSinks();if(!sinks.isEmpty()){StringsinkName=sinks.get(0).get("name");driver.startTabMirroring(sinkName);driver.stopCasting(sinkName);}driver.quit();}@TestpublicvoidgetBrowserLogs(){EdgeDriverdriver=newEdgeDriver();driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");WebElementconsoleLogButton=driver.findElement(By.id("consoleError"));consoleLogButton.click();LogEntrieslogs=driver.manage().logs().get(LogType.BROWSER);// Assert that at least one log contains the expected messagebooleanlogFound=false;for(LogEntrylog:logs){if(log.getMessage().contains("I am console error")){logFound=true;break;}}Assertions.assertTrue(logFound,"No matching log message found.");driver.quit();}}
importosimportreimportsubprocessimportpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_options():options=get_default_edge_options()driver=webdriver.Edge(options=options)driver.quit()deftest_args():options=get_default_edge_options()options.add_argument("--start-maximized")driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_set_browser_location(edge_bin):options=get_default_edge_options()options.binary_location=edge_bindriver=webdriver.Edge(options=options)driver.quit()deftest_add_extension():options=get_default_edge_options()extension_file_path=os.path.abspath("tests/extensions/webextensions-selenium-example.crx")options.add_extension(extension_file_path)driver=webdriver.Edge(options=options)driver.get("https://www.selenium.dev/selenium/web/blank.html")driver.quit()deftest_keep_browser_open():options=get_default_edge_options()options.add_experimental_option("detach",True)driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_exclude_switches():options=get_default_edge_options()options.add_experimental_option('excludeSwitches',['disable-popup-blocking'])driver=webdriver.Edge(options=options)driver.get('http://selenium.dev')driver.quit()deftest_log_to_file(log_path):service=webdriver.EdgeService(log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asfp:assert"Starting Microsoft Edge WebDriver"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.EdgeService(log_output=subprocess.STDOUT)driver=webdriver.Edge(service=service)out,err=capfd.readouterr()assert"Starting Microsoft Edge WebDriver"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.EdgeService(service_args=['--log-level=DEBUG'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assert'[DEBUG]'inf.read()driver.quit()deftest_log_features(log_path):service=webdriver.EdgeService(service_args=['--append-log','--readable-timestamp'],log_output=log_path)driver=webdriver.Edge(service=service)withopen(log_path,'r')asf:assertre.match(r"\[\d\d-\d\d-\d\d\d\d",f.read())driver.quit()deftest_build_checks(log_path):service=webdriver.EdgeService(service_args=['--disable-build-check'],log_output=log_path)driver=webdriver.Edge(service=service)expected="[WARNING]: You are using an unsupported command-line switch: --disable-build-check"withopen(log_path,'r')asf:assertexpectedinf.read()driver.quit()deftest_set_network_conditions():driver=webdriver.Edge()network_conditions={"offline":False,"latency":20,# 20 ms of latency"download_throughput":2000*1024/8,# 2000 kbps"upload_throughput":2000*1024/8,# 2000 kbps}driver.set_network_conditions(**network_conditions)driver.get("https://www.selenium.dev")# check whether the network conditions are setassertdriver.get_network_conditions()==network_conditionsdriver.quit()deftest_set_permissions():driver=webdriver.Edge()driver.get('https://www.selenium.dev')driver.set_permissions('camera','denied')assertget_permission_state(driver,'camera')=='denied'driver.quit()defget_permission_state(driver,name):"""Helper function to query the permission state."""script="""
const callback = arguments[arguments.length - 1];
navigator.permissions.query({name: arguments[0]}).then(permissionStatus => {
callback(permissionStatus.state);
});
"""returndriver.execute_async_script(script,name)deftest_cast_features():driver=webdriver.Edge()try:sinks=driver.get_sinks()ifsinks:sink_name=sinks[0]['name']driver.start_tab_mirroring(sink_name)driver.stop_casting(sink_name)else:pytest.skip("No available Cast sinks to test with.")finally:driver.quit()deftest_get_browser_logs():driver=webdriver.Edge()driver.get("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html")driver.find_element(By.ID,"consoleError").click()logs=driver.get_log("browser")# Assert that at least one log contains the expected messageassertany("I am console error"inlog['message']forloginlogs),"No matching log message found."driver.quit()defget_default_edge_options():options=webdriver.EdgeOptions()options.add_argument("--no-sandbox")returnoptions
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Edge'dodescribe'Options'dolet(:edge_location){driver_finder&&ENV.fetch('EDGE_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.edge@driver=Selenium::WebDriver.for:edge,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.edgeoptions.args<<'--start-maximized'@driver=Selenium::WebDriver.for:edge,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.edgeoptions.binary=edge_location@driver=Selenium::WebDriver.for:edge,options:optionsendit'add extensions'doextension_file_path=File.expand_path('../spec_support/extensions/webextensions-selenium-example.crx',__dir__)options=Selenium::WebDriver::Options.edgeoptions.add_extension(extension_file_path)@driver=Selenium::WebDriver.for:edge,options:options@driver.get('https://www.selenium.dev/selenium/web/blank.html')injected=@driver.find_element(:id,'webextensions-selenium-example')expect(injected.text).toeq'Content injected by webextensions-selenium-example'endit'keeps browser open'dooptions=Selenium::WebDriver::Options.edgeoptions.detach=true@driver=Selenium::WebDriver.for:edge,options:optionsendit'excludes switches'dooptions=Selenium::WebDriver::Options.edgeoptions.exclude_switches<<'disable-popup-blocking'@driver=Selenium::WebDriver.for:edge,options:optionsendenddescribe'Service'dolet(:file_name){File.expand_path('msedgedriver.log')}after{FileUtils.rm_f(file_name)}it'logs to file'doservice=Selenium::WebDriver::Service.edgeservice.log=file_name@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).first).toinclude('Starting Microsoft Edge WebDriver')endit'logs to console'doservice=Selenium::WebDriver::Service.edgeservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:edge,service:service}.tooutput(/Starting Microsoft Edge WebDriver/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.edgeservice.log=file_nameservice.args<<'--log-level=DEBUG'@driver=Selenium::WebDriver.for:edge,service:serviceexpect(File.readlines(file_name).grep(/\[DEBUG\]:/).any?).toeqtrueendit'sets log features'doargs=["--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:serviceexpect(File.readlines(file_name).grep(/\[\d\d-\d\d-\d\d\d\d/).any?).toeqtrueendit'disables build checks'doservice=Selenium::WebDriver::Service.edgelog:file_name,args:['--verbose']service.args<<'--disable-build-check'@driver=Selenium::WebDriver.for:edge,service:servicewarning=/\[WARNING\]: You are using an unsupported command-line switch: --disable-build-check/expect(File.readlines(file_name).grep(warning).any?).toeqtrueendenddescribe'Special Features'doit'casts'do@driver=Selenium::WebDriver.for:edgesinks=@driver.cast_sinksunlesssinks.empty?device_name=sinks.first['name']@driver.start_cast_tab_mirroring(device_name)expect{@driver.stop_casting(device_name)}.not_toraise_exceptionendendit'gets and sets network conditions'do@driver=Selenium::WebDriver.for:edge@driver.network_conditions={offline:false,latency:100,throughput:200}expect(@driver.network_conditions).toeq('offline'=>false,'latency'=>100,'download_throughput'=>200,'upload_throughput'=>200)endit'gets the browser logs'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'sleep1logs=@driver.logs.get(:browser)expect(logs.first.message).toinclude'Failed to load resource'endit'sets permissions'do@driver=Selenium::WebDriver.for:edge@driver.navigate.to'https://www.selenium.dev/selenium/web/'@driver.add_permission('camera','denied')@driver.add_permissions('clipboard-read'=>'denied','clipboard-write'=>'prompt')expect(permission('camera')).toeq('denied')expect(permission('clipboard-read')).toeq('denied')expect(permission('clipboard-write')).toeq('prompt')endenddefdriver_finderoptions=Selenium::WebDriver::Options.edge(browser_version:'stable')service=Selenium::WebDriver::Service.edgefinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['EDGEDRIVER_BIN']=finder.driver_pathENV['EDGE_BIN']=finder.browser_pathenddefpermission(name)@driver.execute_async_script('callback = arguments[arguments.length - 1];'\'callback(navigator.permissions.query({name: arguments[0]}));',name)['state']endend
See the [Chrome DevTools] section for more information about using DevTools in Edge
3 - Funcionalidade específica do Firefox
Estas capacidades e características são específicas ao navegador Mozilla Firefox.
Por omissão, Selenium 4 é compatível com Firefox 78 ou superior. Recomendamos que use sempre a versão mais recente do geckodriver.
Opções
Capacidades comuns a todos os navegadores estão descritas na página Opções.
Capacidades únicas ao Firefox podem ser encontradas na página da Mozilla para firefoxOptions
Este é um exemplo de como iniciar uma sessão Firefox com um conjunto de opções básicas:
3538
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['–log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['–log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['–log-no-truncate','–log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' … 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['–profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_firefox.py#L10-L11" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
3336
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Firefox;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassFirefoxTest{privateFirefoxDriverdriver;privatestring_logLocation;privatestring_tempPath; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newFirefoxOptions();driver=newFirefoxDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newFirefoxOptions();options.AddArgument("-headless");driver=newFirefoxDriver(options);} [TestMethod]publicvoidSetBinary(){varoptions=newFirefoxOptions();options.BinaryLocation=GetFirefoxLocation();driver=newFirefoxDriver(options);} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToFile(){varservice=FirefoxDriverService.CreateDefaultService();//service.LogFile = _logLocationdriver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("geckodriver INFO Listening on")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=FirefoxDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newFirefoxDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("You can set it, just can't see it")]publicvoidLogsLevel(){varservice=FirefoxDriverService.CreateDefaultService();//service.LogFile = _logLocationservice.LogLevel=FirefoxDriverLogLevel.Debug;driver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Marionette\tDEBUG")));} [TestMethod] [Ignore("Not implemented")]publicvoidStopsTruncatingLogs(){varservice=FirefoxDriverService.CreateDefaultService();//service.TruncateLogs = false;service.LogLevel=FirefoxDriverLogLevel.Debug;driver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNull(lines.FirstOrDefault(line=>line.Contains(" ... ")));} [TestMethod] [Ignore("Not implemented")]publicvoidSetProfileLocation(){varservice=FirefoxDriverService.CreateDefaultService();// service.ProfileRoot = GetTempDirectory();driver=newFirefoxDriver(service);stringprofile=(string)driver.Capabilities.GetCapability("moz:profile");string[]directories=profile.Split("/");vardirName=directories.Last();Assert.AreEqual(GetTempDirectory()+"/"+dirName,profile);} [TestMethod]publicvoidInstallAddon(){SetWaitingDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.xpi");driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidUnInstallAddon(){driver=newFirefoxDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.xpi");stringextensionId=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]publicvoidInstallUnsignedAddon(){SetWaitingDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionDirPath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example/");driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath),true);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);}privatestringGetLogLocation(){if(_logLocation!=null&&!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath!=null&&!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatevoidSetWaitingDriver(){driver=newFirefoxDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(2);}privatestaticstringGetFirefoxLocation(){varoptions=newFirefoxOptions(){BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
Alguns exemplos de uso com capacidades diferentes:
Argumentos
O parametro args é usado para indicar uma lista de opções ao iniciar o navegador.
Opções mais frequentes incluem -headless e "-profile", "/path/to/profile"
Adicione uma opção:
4345
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
const{Browser,By,Builder}=require('selenium-webdriver');constFirefox=require('selenium-webdriver/firefox');constoptions=newFirefox.Options();constpath=require('path');constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.FIREFOX).setFirefoxOptions(options.addArguments('--headless')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to add extension',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example.xpi')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});it('Should be able to install unsigned addon',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath,true);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});});
O parametro binary é usado contendo o caminho para uma localização específica do navegador.
Como exemplo, pode usar este parametro para indicar ao geckodriver a versão Firefox Nightly ao invés da
versão de produção, quando ambas versões estão presentes no seu computador.
Adicionar uma localização:
5355
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['–log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['–log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['–log-no-truncate','–log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' … 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['–profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_firefox.py#L28" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
5254
Show full example
usingSystem;usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Firefox;namespaceSeleniumDocs.Browsers{ [TestClass]publicclassFirefoxTest{privateFirefoxDriverdriver;privatestring_logLocation;privatestring_tempPath; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}driver.Quit();} [TestMethod]publicvoidBasicOptions(){varoptions=newFirefoxOptions();driver=newFirefoxDriver(options);} [TestMethod]publicvoidArguments(){varoptions=newFirefoxOptions();options.AddArgument("-headless");driver=newFirefoxDriver(options);} [TestMethod]publicvoidSetBinary(){varoptions=newFirefoxOptions();options.BinaryLocation=GetFirefoxLocation();driver=newFirefoxDriver(options);} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToFile(){varservice=FirefoxDriverService.CreateDefaultService();//service.LogFile = _logLocationdriver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("geckodriver INFO Listening on")));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=FirefoxDriverService.CreateDefaultService();//service.LogToConsole = true;driver=newFirefoxDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod] [Ignore("You can set it, just can't see it")]publicvoidLogsLevel(){varservice=FirefoxDriverService.CreateDefaultService();//service.LogFile = _logLocationservice.LogLevel=FirefoxDriverLogLevel.Debug;driver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Marionette\tDEBUG")));} [TestMethod] [Ignore("Not implemented")]publicvoidStopsTruncatingLogs(){varservice=FirefoxDriverService.CreateDefaultService();//service.TruncateLogs = false;service.LogLevel=FirefoxDriverLogLevel.Debug;driver=newFirefoxDriver(service);varlines=File.ReadLines(GetLogLocation());Assert.IsNull(lines.FirstOrDefault(line=>line.Contains(" ... ")));} [TestMethod] [Ignore("Not implemented")]publicvoidSetProfileLocation(){varservice=FirefoxDriverService.CreateDefaultService();// service.ProfileRoot = GetTempDirectory();driver=newFirefoxDriver(service);stringprofile=(string)driver.Capabilities.GetCapability("moz:profile");string[]directories=profile.Split("/");vardirName=directories.Last();Assert.AreEqual(GetTempDirectory()+"/"+dirName,profile);} [TestMethod]publicvoidInstallAddon(){SetWaitingDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.xpi");driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);} [TestMethod]publicvoidUnInstallAddon(){driver=newFirefoxDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionFilePath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example.xpi");stringextensionId=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]publicvoidInstallUnsignedAddon(){SetWaitingDriver();stringbaseDir=AppDomain.CurrentDomain.BaseDirectory;stringextensionDirPath=Path.Combine(baseDir,"../../../Extensions/webextensions-selenium-example/");driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath),true);driver.Url="https://www.selenium.dev/selenium/web/blank.html";IWebElementinjected=driver.FindElement(By.Id("webextensions-selenium-example"));Assert.AreEqual("Content injected by webextensions-selenium-example",injected.Text);}privatestringGetLogLocation(){if(_logLocation!=null&&!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath!=null&&!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatevoidSetWaitingDriver(){driver=newFirefoxDriver();driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(2);}privatestaticstringGetFirefoxLocation(){varoptions=newFirefoxOptions(){BrowserVersion="stable"};returnnewDriverFinder(options).GetBrowserPath();}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
Existem várias formas de trabalhar com perfis Firefox
210217
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
const{Builder}=require("selenium-webdriver");constfirefox=require('selenium-webdriver/firefox');constoptions=newfirefox.Options();letprofile='/path to custom profile';options.setProfile(profile);constdriver=newBuilder().forBrowser('firefox').setFirefoxOptions(options).build();
Note: Whether you create an empty FirefoxProfile or point it to the directory of your own profile, Selenium
will create a temporary directory to store either the data of the new profile or a copy of your existing one. Every
time you run your program, a different temporary directory will be created. These directories are not cleaned up
explicitly by Selenium, they should eventually get removed by the operating system. However, if you want to remove
the copy manually (e.g. if your profile is large in size), the path of the copy is exposed by the FirefoxProfile
object. Check the language specific implementation to see how to retrieve that location.
If you want to use an existing Firefox profile, you can pass in the path to that profile. Please refer to the official
Firefox documentation
for instructions on how to find the directory of your profile.
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you
direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" … "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java#L62-L63" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" … "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java#L76-L77" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" … "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java#L90-L91" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" … "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java#L106-L107" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: Java also allows setting log level by System Property: Property key: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE Property value: "true" or "false"
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
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:
importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" … "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/FirefoxTest.java#L118-L119" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
8082
Show full example
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
const{Browser,By,Builder}=require('selenium-webdriver');constFirefox=require('selenium-webdriver/firefox');constoptions=newFirefox.Options();constpath=require('path');constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.FIREFOX).setFirefoxOptions(options.addArguments('--headless')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to add extension',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example.xpi')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});it('Should be able to install unsigned addon',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath,true);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});});
Desinstalar uma extensão implica saber o seu id que pode ser obtido como valor de retorno durante a instalação.
147149
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
const{Browser,By,Builder}=require('selenium-webdriver');constFirefox=require('selenium-webdriver/firefox');constoptions=newFirefox.Options();constpath=require('path');constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.FIREFOX).setFirefoxOptions(options.addArguments('--headless')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to add extension',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example.xpi')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});it('Should be able to install unsigned addon',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath,true);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});});
Quando trabalhar em uma extensão não terminada ou não publicada, provavelmente ela não estará assinada.
Desta forma, só pode ser instalada como “temporária”. Isto pode ser feito passando uma arquivo ZIP ou
uma pasta, este é um exemplo com uma pasta:
159161
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
const{Browser,By,Builder}=require('selenium-webdriver');constFirefox=require('selenium-webdriver/firefox');constoptions=newFirefox.Options();constpath=require('path');constassert=require("assert");describe('Should be able to Test Command line arguments',function(){it('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.FIREFOX).setFirefoxOptions(options.addArguments('--headless')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to add extension',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example.xpi')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});it('Should be able to install unsigned addon',asyncfunction(){constxpiPath=path.resolve('./test/resources/extensions/selenium-example')letdriver=newBuilder().forBrowser(Browser.FIREFOX).build()letid=awaitdriver.installAddon(xpiPath,true);awaitdriver.uninstallAddon(id);awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');constele=awaitdriver.findElements(By.id("webextensions-selenium-example"));assert.equal(ele.length,0);awaitdriver.quit();});});
The following examples are for local webdrivers. For remote webdrivers,
please refer to the
Remote WebDriver page.
180182
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
The following examples are for local webdrivers. For remote webdrivers,
please refer to the
Remote WebDriver page.
196199
Show full example
packagedev.selenium.browsers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.Paths;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.DisabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.By;importorg.openqa.selenium.OutputType;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.firefox.*;importorg.openqa.selenium.remote.service.DriverFinder;publicclassFirefoxTestextendsBaseTest{privateFirefoxDriverdriver;@AfterEachpublicvoidclearProperties(){System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY);System.clearProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY);driver.quit();}@TestpublicvoidbasicOptions(){FirefoxOptionsoptions=newFirefoxOptions();driver=newFirefoxDriver(options);}@Testpublicvoidarguments(){FirefoxOptionsoptions=newFirefoxOptions();options.addArguments("-headless");driver=newFirefoxDriver(options);}@Test@DisabledOnOs(OS.WINDOWS)publicvoidsetBrowserLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBinary(getFirefoxLocation());driver=newFirefoxDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{FilelogLocation=getTempFile("logsToFile",".log");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogFile(logLocation).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsToConsole()throwsIOException{FilelogLocation=getTempFile("logsToConsole",".log");System.setOut(newPrintStream(logLocation));FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogOutput(System.out).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("geckodriver INFO Listening on"));}@TestpublicvoidlogsWithLevel()throwsIOException{FilelogLocation=getTempFile("logsWithLevel",".log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertTrue(fileContent.contains("Marionette\tDEBUG"));}@TestpublicvoidstopsTruncatingLogs()throwsIOException{FilelogLocation=getTempFile("geckodriver-","log");System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY,logLocation.getAbsolutePath());System.setProperty(GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY,FirefoxDriverLogLevel.DEBUG.toString());FirefoxDriverServiceservice=newGeckoDriverService.Builder().withTruncatedLogs(false).build();driver=newFirefoxDriver(service);StringfileContent=newString(Files.readAllBytes(logLocation.toPath()));Assertions.assertFalse(fileContent.contains(" ... "));}@TestpublicvoidsetProfileLocation(){FileprofileDirectory=getTempDirectory("profile-");FirefoxDriverServiceservice=newGeckoDriverService.Builder().withProfileRoot(profileDirectory).build();driver=newFirefoxDriver(service);Stringlocation=(String)driver.getCapabilities().getCapability("moz:profile");Assertions.assertTrue(location.contains(profileDirectory.getAbsolutePath()));}@TestpublicvoidinstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");driver.installExtension(xpiPath);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=driver.findElement(By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}@TestpublicvoiduninstallAddon(){driver=startFirefoxDriver();PathxpiPath=Paths.get("src/test/resources/extensions/selenium-example.xpi");Stringid=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);}@TestpublicvoidinstallUnsignedAddonPath(){driver=startFirefoxDriver();Pathpath=Paths.get("src/test/resources/extensions/selenium-example");driver.installExtension(path,true);driver.get("https://www.selenium.dev/selenium/web/blank.html");WebElementinjected=getLocatedElement(driver,By.id("webextensions-selenium-example"));Assertions.assertEquals("Content injected by webextensions-selenium-example",injected.getText());}privatePathgetFirefoxLocation(){FirefoxOptionsoptions=newFirefoxOptions();options.setBrowserVersion("stable");DriverFinderfinder=newDriverFinder(GeckoDriverService.createDefaultService(),options);returnPath.of(finder.getBrowserPath());}@TestpublicvoidfullPageScreenshot()throwsException{driver=startFirefoxDriver();driver.get("https://www.selenium.dev");Filescreenshot=driver.getFullPageScreenshotAs(OutputType.FILE);FiletargetFile=newFile("full_page_screenshot.png");Files.move(screenshot.toPath(),targetFile.toPath());// Verify the screenshot file existsAssertions.assertTrue(targetFile.exists(),"The full page screenshot file should exist");Files.deleteIfExists(targetFile.toPath());driver.quit();}@TestpublicvoidsetContext(){driver=startFirefoxDriver();((HasContext)driver).setContext(FirefoxCommandContext.CHROME);driver.executeScript("console.log('Inside Chrome context');");// Verify the context is back to "content"Assertions.assertEquals(FirefoxCommandContext.CHROME,((HasContext)driver).getContext(),"The context should be 'chrome'");driver.quit();}@TestpublicvoidfirefoxProfile(){FirefoxProfileprofile=newFirefoxProfile();FirefoxOptionsoptions=newFirefoxOptions();profile.setPreference("javascript.enabled","False");options.setProfile(profile);driver=newFirefoxDriver(options);driver.quit();}}
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriverdeftest_basic_options():options=webdriver.FirefoxOptions()driver=webdriver.Firefox(options=options)driver.quit()deftest_arguments():options=webdriver.FirefoxOptions()options.add_argument("-headless")driver=webdriver.Firefox(options=options)driver.quit()deftest_set_browser_location(firefox_bin):options=webdriver.FirefoxOptions()options.binary_location=firefox_bindriver=webdriver.Firefox(options=options)driver.quit()deftest_log_to_file(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)driver.get("https://www.selenium.dev")withopen(log_path,'r')asfp:assert"geckodriver INFO Listening on"infp.readline()driver.quit()deftest_log_to_stdout(capfd):service=webdriver.FirefoxService(log_output=subprocess.STDOUT)driver=webdriver.Firefox(service=service)out,err=capfd.readouterr()assert"geckodriver INFO Listening on"inoutdriver.quit()deftest_log_level(log_path):service=webdriver.FirefoxService(log_output=log_path,service_args=['--log','debug'])driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert'\tDEBUG'inf.read()driver.quit()deftest_log_truncation(log_path):service=webdriver.FirefoxService(service_args=['--log-no-truncate','--log','debug'],log_output=log_path)driver=webdriver.Firefox(service=service)withopen(log_path,'r')asf:assert' ... 'notinf.read()driver.quit()deftest_profile_location(temp_dir):service=webdriver.FirefoxService(service_args=['--profile-root',temp_dir])driver=webdriver.Firefox(service=service)profile_name=driver.capabilities.get('moz:profile').replace('\\','/').split('/')[-1]assertprofile_nameinos.listdir(temp_dir)driver.quit()deftest_install_addon(firefox_driver,addon_path_xpi):driver=firefox_driverdriver.install_addon(addon_path_xpi)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_uninstall_addon(firefox_driver,addon_path_xpi):driver=firefox_driverid=driver.install_addon(addon_path_xpi)driver.uninstall_addon(id)driver.get("https://www.selenium.dev/selenium/web/blank.html")assertlen(driver.find_elements(webdriver.common.by.By.ID,"webextensions-selenium-example"))==0deftest_install_unsigned_addon_directory(firefox_driver,addon_path_dir):driver=firefox_driverdriver.install_addon(addon_path_dir,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_install_unsigned_addon_directory_slash(firefox_driver,addon_path_dir_slash):driver=firefox_driverdriver.install_addon(addon_path_dir_slash,temporary=True)driver.get("https://www.selenium.dev/selenium/web/blank.html")injected=driver.find_element(webdriver.common.by.By.ID,"webextensions-selenium-example")assertinjected.text=="Content injected by webextensions-selenium-example"deftest_full_page_screenshot(firefox_driver):driver=firefox_driverdriver.get("https://www.selenium.dev")driver.save_full_page_screenshot("full_page_screenshot.png")assertos.path.exists("full_page_screenshot.png")driver.quit()deftest_set_context(firefox_driver):driver=firefox_driverwithdriver.context(driver.CONTEXT_CHROME):driver.execute_script("console.log('Inside Chrome context');")# Check if the context is back to contentassertdriver.execute("GET_CONTEXT")["value"]=="content"deftest_firefox_profile():fromselenium.webdriver.firefox.optionsimportOptionsfromselenium.webdriver.firefox.firefox_profileimportFirefoxProfileoptions=Options()firefox_profile=FirefoxProfile()firefox_profile.set_preference("javascript.enabled",False)options.profile=firefox_profiledriver=webdriver.Firefox(options=options)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Firefox'dodescribe'Options'dolet(:firefox_location){driver_finder&&ENV.fetch('FIREFOX_BIN',nil)}it'basic options'dooptions=Selenium::WebDriver::Options.firefox@driver=Selenium::WebDriver.for:firefox,options:optionsendit'add arguments'dooptions=Selenium::WebDriver::Options.firefoxoptions.args<<'-headless'@driver=Selenium::WebDriver.for:firefox,options:optionsendit'sets location of binary'dooptions=Selenium::WebDriver::Options.firefoxoptions.binary=firefox_location@driver=Selenium::WebDriver.for:firefox,options:optionsendenddescribe'Service'dolet(:file_name){Tempfile.new('geckodriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.rm_rf(root_directory)endit'logs to file'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_name@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).first).toinclude("geckodriver\tINFO\tListening on")endit'logs to console'doservice=Selenium::WebDriver::Service.firefoxservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:firefox,service:service}.tooutput(/geckodriver INFO Listening on/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.firefoxservice.log=file_nameservice.args+=%w[--log debug]@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/Marionette DEBUG/).any?).toeqtrueendit'stops truncating log lines'doservice=Selenium::WebDriver::Service.firefox(log:file_name,args:%w[--log debug])service.args<<'--log-no-truncate'@driver=Selenium::WebDriver.for:firefox,service:serviceexpect(File.readlines(file_name).grep(/ \.\.\. /).any?).toeqfalseendit'sets default profile location'doservice=Selenium::WebDriver::Service.firefoxservice.args+=['--profile-root',root_directory]@driver=Selenium::WebDriver.for:firefox,service:serviceprofile_location=Dir.new(@driver.capabilities['moz:profile'])expect(profile_location.path.gsub('\\','/')).toinclude(root_directory)endenddescribe'Features'dolet(:driver){start_firefox}it'installs addon'doextension_file_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'uninstalls addon'doextension_file_path=File.expand_path('../spec_support/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')).tobe_emptyendit'installs unsigned addon'doextension_dir_path=File.expand_path('../spec_support/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).toeq'Content injected by webextensions-selenium-example'endit'takes full page screenshot'dodriver.navigate.to'https://www.selenium.dev/selenium/web/blank.html'Dir.mktmpdir('screenshot_test')do|dir|screenshot=driver.save_full_page_screenshot(File.join(dir,'screenshot.png'))expect(screenshot).tobe_aFileendendit'sets the context'dodriver.context='content'expect(driver.context).toeq'content'endenddescribe'Profile'doit'creates a new profile'doprofile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']='/tmp/webdriver-downloads'options=Selenium::WebDriver::Firefox::Options.new(profile:profile)expect(options.profile).toeq(profile)endenddefdriver_finderoptions=Selenium::WebDriver::Options.firefox(browser_version:'stable')service=Selenium::WebDriver::Service.firefoxfinder=Selenium::WebDriver::DriverFinder.new(options,service)ENV['GECKODRIVER_BIN']=finder.driver_pathENV['FIREFOX_BIN']=finder.browser_pathendend
Note: As of Firefox 138, geckodriver needs to be started with the argument --allow-system-access to switch the context to CHROME.
4 - Funcionalidade específica do IE
Estas capacidades e características são específicas ao navegador Microsoft Internet Explorer.
Desde Junho de 2022, o Projecto Selenium deixou de suportar oficialmente o navegador Internet Explorer.
O driver Internet Explorer continua a suportar a execução do Microsoft Edge no modo “IE Compatibility Mode.”
Considerações especiais
O IE Driver é o único driver mantido directamente pelo Projecto Selenium.
Embora existam binários para as versões de 32 e 64 bits, existem algumas
limitações conhecidas
com o driver de 64 bits. Desta forma, recomenda-se a utilização do driver de 32 bits.
Informação adicional sobre como usar o Internet Explorer pode ser encontrada na
página IE Driver Server
Opções
Este é um exemplo de como iniciar o navegador Microsoft Edge em modo compatibilidade Internet Explorer
usando um conjunto de opções básicas:
3742
Show full example
packagedev.selenium.browsers;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.EnabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.ie.InternetExplorerDriver;importorg.openqa.selenium.ie.InternetExplorerDriverLogLevel;importorg.openqa.selenium.ie.InternetExplorerDriverService;importorg.openqa.selenium.ie.InternetExplorerOptions;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;@EnabledOnOs(OS.WINDOWS)publicclassInternetExplorerTest{publicInternetExplorerDriverdriver;privateFilelogLocation;privateFiletempDirectory;@AfterEachpublicvoidquit(){if(logLocation!=null&&logLocation.exists()){logLocation.delete();}if(tempDirectory!=null&&tempDirectory.exists()){tempDirectory.delete();}driver.quit();}@TestpublicvoidbasicOptionsWin10(){InternetExplorerOptionsoptions=newInternetExplorerOptions();options.attachToEdgeChrome();options.withEdgeExecutablePath(getEdgeLocation());driver=newInternetExplorerDriver(options);}@TestpublicvoidbasicOptionsWin11(){InternetExplorerOptionsoptions=newInternetExplorerOptions();driver=newInternetExplorerDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogFile(getLogLocation()).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsToConsole()throwsIOException{System.setOut(newPrintStream(getLogLocation()));InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogOutput(System.out).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsWithLevel()throwsIOException{System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,getLogLocation().getAbsolutePath());InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogLevel(InternetExplorerDriverLogLevel.WARN).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));}@TestpublicvoidsupportingFilesLocation()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withExtractPath(getTempDirectory()).build();driver=newInternetExplorerDriver(service);Assertions.assertTrue(newFile(getTempDirectory()+"/IEDriver.tmp").exists());}privateFilegetLogLocation()throwsIOException{if(logLocation==null||!logLocation.exists()){logLocation=File.createTempFile("iedriver-",".log");}returnlogLocation;}privateFilegetTempDirectory()throwsIOException{if(tempDirectory==null||!tempDirectory.exists()){tempDirectory=Files.createTempDirectory("supporting-").toFile();}returntempDirectory;}privateStringgetEdgeLocation(){returnSystem.getenv("EDGE_BIN");}}
importsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["–silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_internet_explorer.py#L11-L14" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium.IE;usingSeleniumDocs.TestSupport;namespaceSeleniumDocs.Browsers{[TestClassCustom][EnabledOnOs("WINDOWS")]publicclassInternetExplorerTest{privateInternetExplorerDriver_driver;privatestring_logLocation;privatestring_tempPath;[TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}_driver.Quit();}[TestMethod]publicvoidBasicOptionsWin10(){varoptions=newInternetExplorerOptions();options.AttachToEdgeChrome=true;options.EdgeExecutablePath=GetEdgeLocation();_driver=newInternetExplorerDriver(options);}[TestMethod]publicvoidBasicOptionsWin11(){varoptions=newInternetExplorerOptions();_driver=newInternetExplorerDriver(options);}[TestMethod][Ignore("Not implemented")]publicvoidLogsToFile(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Console.WriteLine("Lines: {0}",lines);Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));}[TestMethod][Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=InternetExplorerDriverService.CreateDefaultService();//service.LogToConsole = true;_driver=newInternetExplorerDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();}[TestMethod]publicvoidLogsLevel(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();service.LoggingLevel=InternetExplorerDriverLogLevel.Warn;_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Invalid capability setting: timeouts is type null")));}[TestMethod]publicvoidSupportingFilesLocation(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LibraryExtractionPath=GetTempDirectory();_driver=newInternetExplorerDriver(service);Assert.IsTrue(File.Exists(GetTempDirectory()+"/IEDriver.tmp"));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath==null||!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatestringGetEdgeLocation(){returnEnvironment.GetEnvironmentVariable("EDGE_BIN");}}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs#L35-L38" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
1621
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
Se o IE não estiver presente no sistema (ausente por omissão no Windows 11), não necessita
usar os parametros “attachToEdgeChrome” e “withEdgeExecutablePath”, pois o IE Driver
irá encontrar e usar o Edge automaticamente.
Se o IE e o Edge estiverem ambos presentes no sistema, use o parametro “attachToEdgeChrome”,
o IE Driver irá encontrar e usar o Edge automaticamente.
So, if IE is not on the system, you only need:
4548
Show full example
packagedev.selenium.browsers;importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.EnabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.ie.InternetExplorerDriver;importorg.openqa.selenium.ie.InternetExplorerDriverLogLevel;importorg.openqa.selenium.ie.InternetExplorerDriverService;importorg.openqa.selenium.ie.InternetExplorerOptions;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;@EnabledOnOs(OS.WINDOWS)publicclassInternetExplorerTest{publicInternetExplorerDriverdriver;privateFilelogLocation;privateFiletempDirectory;@AfterEachpublicvoidquit(){if(logLocation!=null&&logLocation.exists()){logLocation.delete();}if(tempDirectory!=null&&tempDirectory.exists()){tempDirectory.delete();}driver.quit();}@TestpublicvoidbasicOptionsWin10(){InternetExplorerOptionsoptions=newInternetExplorerOptions();options.attachToEdgeChrome();options.withEdgeExecutablePath(getEdgeLocation());driver=newInternetExplorerDriver(options);}@TestpublicvoidbasicOptionsWin11(){InternetExplorerOptionsoptions=newInternetExplorerOptions();driver=newInternetExplorerDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogFile(getLogLocation()).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsToConsole()throwsIOException{System.setOut(newPrintStream(getLogLocation()));InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogOutput(System.out).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsWithLevel()throwsIOException{System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,getLogLocation().getAbsolutePath());InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogLevel(InternetExplorerDriverLogLevel.WARN).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));}@TestpublicvoidsupportingFilesLocation()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withExtractPath(getTempDirectory()).build();driver=newInternetExplorerDriver(service);Assertions.assertTrue(newFile(getTempDirectory()+"/IEDriver.tmp").exists());}privateFilegetLogLocation()throwsIOException{if(logLocation==null||!logLocation.exists()){logLocation=File.createTempFile("iedriver-",".log");}returnlogLocation;}privateFilegetTempDirectory()throwsIOException{if(tempDirectory==null||!tempDirectory.exists()){tempDirectory=Files.createTempDirectory("supporting-").toFile();}returntempDirectory;}privateStringgetEdgeLocation(){returnSystem.getenv("EDGE_BIN");}}
importsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["–silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/python/tests/browsers/test_internet_explorer.py#L21-L22" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium.IE;usingSeleniumDocs.TestSupport;namespaceSeleniumDocs.Browsers{[TestClassCustom][EnabledOnOs("WINDOWS")]publicclassInternetExplorerTest{privateInternetExplorerDriver_driver;privatestring_logLocation;privatestring_tempPath;[TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}_driver.Quit();}[TestMethod]publicvoidBasicOptionsWin10(){varoptions=newInternetExplorerOptions();options.AttachToEdgeChrome=true;options.EdgeExecutablePath=GetEdgeLocation();_driver=newInternetExplorerDriver(options);}[TestMethod]publicvoidBasicOptionsWin11(){varoptions=newInternetExplorerOptions();_driver=newInternetExplorerDriver(options);}[TestMethod][Ignore("Not implemented")]publicvoidLogsToFile(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Console.WriteLine("Lines: {0}",lines);Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));}[TestMethod][Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=InternetExplorerDriverService.CreateDefaultService();//service.LogToConsole = true;_driver=newInternetExplorerDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();}[TestMethod]publicvoidLogsLevel(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();service.LoggingLevel=InternetExplorerDriverLogLevel.Warn;_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Invalid capability setting: timeouts is type null")));}[TestMethod]publicvoidSupportingFilesLocation(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LibraryExtractionPath=GetTempDirectory();_driver=newInternetExplorerDriver(service);Assert.IsTrue(File.Exists(GetTempDirectory()+"/IEDriver.tmp"));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath==null||!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatestringGetEdgeLocation(){returnEnvironment.GetEnvironmentVariable("EDGE_BIN");}}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/dotnet/SeleniumDocs/Browsers/InternetExplorerTest.cs#L44-L45" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
2326
Show full example
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
<p><ahref=/documentation/about/contributing/#moving-examples><spanclass="selenium-badge-code"data-bs-toggle="tooltip"data-bs-placement="right"title="One or more of these examples need to be implemented in the examples directory; click for details in the contribution guide">MoveCode</span></a></p>valoptions=InternetExplorerOptions()valdriver=InternetExplorerDriver(options)
Aqui pode ver alguns exemplos de utilização com capacidades diferentes:
fileUploadDialogTimeout
Em alguns ambientes, o Internet Explorer pode expirar ao abrir a
Caixa de Diálogo de upload de arquivo. O IEDriver tem um tempo limite padrão de 1000 ms, mas você
pode aumentar o tempo limite usando o recurso fileUploadDialogTimeout.
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
Quando definido como true, este recurso limpa o Cache,
Histórico do navegador e cookies para todas as instâncias em execução
do InternetExplorer, incluindo aquelas iniciadas manualmente
ou pelo driver. Por padrão, é definido como false.
Usar este recurso causará queda de desempenho quando
iniciar o navegador, pois o driver irá esperar até que o cache
seja limpo antes de iniciar o navegador IE.
Esse recurso aceita um valor booleano como parâmetro.
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
O driver do InternetExplorer espera que o nível de zoom do navegador seja de 100%,
caso contrário, o driver lançará uma exceção. Este comportamento padrão
pode ser desativado definindo ignoreZoomSetting como true.
Esse recurso aceita um valor booleano como parâmetro.
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
Se deve ignorar a verificação do Modo protegido durante o lançamento
uma nova sessão do IE.
Se não for definido e as configurações do Modo protegido não forem iguais para
todas as zonas, uma exceção será lançada pelo driver.
Se a capacidade for definida como true, os testes podem
tornar-se instáveis, não responderem ou os navegadores podem travar.
No entanto, esta ainda é de longe a segunda melhor escolha,
e a primeira escolha sempre deve ser
definir as configurações do Modo protegido de cada zona manualmente.
Se um usuário estiver usando esta propriedade,
apenas um “melhor esforço” no suporte será dado.
Esse recurso aceita um valor booleano como parâmetro.
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
O Internet Explorer inclui várias opções de linha de comando
que permitem solucionar problemas e configurar o navegador.
Os seguintes pontos descrevem algumas opções de linha de comando com suporte
-private: Usado para iniciar o IE no modo de navegação privada. Isso funciona para o IE 8 e versões posteriores.
-k: Inicia o Internet Explorer no modo quiosque.
O navegador é aberto em uma janela maximizada que não exibe a barra de endereço, os botões de navegação ou a barra de status.
-extoff: Inicia o IE no modo sem add-on.
Esta opção é usada especificamente para solucionar problemas com complementos do navegador. Funciona no IE 7 e versões posteriores.
Nota: forceCreateProcessApi deve ser habilitado para que os argumentos da linha de comando funcionem.
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
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:
importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.EnabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.ie.InternetExplorerDriver;importorg.openqa.selenium.ie.InternetExplorerDriverLogLevel;importorg.openqa.selenium.ie.InternetExplorerDriverService;importorg.openqa.selenium.ie.InternetExplorerOptions;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;@EnabledOnOs(OS.WINDOWS)publicclassInternetExplorerTest{publicInternetExplorerDriverdriver;privateFilelogLocation;privateFiletempDirectory;@AfterEachpublicvoidquit(){if(logLocation!=null&&logLocation.exists()){logLocation.delete();}if(tempDirectory!=null&&tempDirectory.exists()){tempDirectory.delete();}driver.quit();}@TestpublicvoidbasicOptionsWin10(){InternetExplorerOptionsoptions=newInternetExplorerOptions();options.attachToEdgeChrome();options.withEdgeExecutablePath(getEdgeLocation());driver=newInternetExplorerDriver(options);}@TestpublicvoidbasicOptionsWin11(){InternetExplorerOptionsoptions=newInternetExplorerOptions();driver=newInternetExplorerDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogFile(getLogLocation()).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsToConsole()throwsIOException{System.setOut(newPrintStream(getLogLocation()));InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogOutput(System.out).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsWithLevel()throwsIOException{System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,getLogLocation().getAbsolutePath());InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogLevel(InternetExplorerDriverLogLevel.WARN).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));}@TestpublicvoidsupportingFilesLocation()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withExtractPath(getTempDirectory()).build();driver=newInternetExplorerDriver(service);Assertions.assertTrue(newFile(getTempDirectory()+"/IEDriver.tmp").exists());}privateFilegetLogLocation()throwsIOException{if(logLocation==null||!logLocation.exists()){logLocation=File.createTempFile("iedriver-",".log");}returnlogLocation;}privateFilegetTempDirectory()throwsIOException{if(tempDirectory==null||!tempDirectory.exists()){tempDirectory=Files.createTempDirectory("supporting-").toFile();}returntempDirectory;}privateStringgetEdgeLocation(){returnSystem.getenv("EDGE_BIN");}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java#L53" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
96100
Show full example
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.EnabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.ie.InternetExplorerDriver;importorg.openqa.selenium.ie.InternetExplorerDriverLogLevel;importorg.openqa.selenium.ie.InternetExplorerDriverService;importorg.openqa.selenium.ie.InternetExplorerOptions;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;@EnabledOnOs(OS.WINDOWS)publicclassInternetExplorerTest{publicInternetExplorerDriverdriver;privateFilelogLocation;privateFiletempDirectory;@AfterEachpublicvoidquit(){if(logLocation!=null&&logLocation.exists()){logLocation.delete();}if(tempDirectory!=null&&tempDirectory.exists()){tempDirectory.delete();}driver.quit();}@TestpublicvoidbasicOptionsWin10(){InternetExplorerOptionsoptions=newInternetExplorerOptions();options.attachToEdgeChrome();options.withEdgeExecutablePath(getEdgeLocation());driver=newInternetExplorerDriver(options);}@TestpublicvoidbasicOptionsWin11(){InternetExplorerOptionsoptions=newInternetExplorerOptions();driver=newInternetExplorerDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogFile(getLogLocation()).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsToConsole()throwsIOException{System.setOut(newPrintStream(getLogLocation()));InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogOutput(System.out).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsWithLevel()throwsIOException{System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,getLogLocation().getAbsolutePath());InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogLevel(InternetExplorerDriverLogLevel.WARN).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));}@TestpublicvoidsupportingFilesLocation()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withExtractPath(getTempDirectory()).build();driver=newInternetExplorerDriver(service);Assertions.assertTrue(newFile(getTempDirectory()+"/IEDriver.tmp").exists());}privateFilegetLogLocation()throwsIOException{if(logLocation==null||!logLocation.exists()){logLocation=File.createTempFile("iedriver-",".log");}returnlogLocation;}privateFilegetTempDirectory()throwsIOException{if(tempDirectory==null||!tempDirectory.exists()){tempDirectory=Files.createTempDirectory("supporting-").toFile();}returntempDirectory;}privateStringgetEdgeLocation(){returnSystem.getenv("EDGE_BIN");}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java#L67" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
importorg.junit.jupiter.api.AfterEach;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.condition.EnabledOnOs;importorg.junit.jupiter.api.condition.OS;importorg.openqa.selenium.ie.InternetExplorerDriver;importorg.openqa.selenium.ie.InternetExplorerDriverLogLevel;importorg.openqa.selenium.ie.InternetExplorerDriverService;importorg.openqa.selenium.ie.InternetExplorerOptions;importjava.io.File;importjava.io.IOException;importjava.io.PrintStream;importjava.nio.file.Files;@EnabledOnOs(OS.WINDOWS)publicclassInternetExplorerTest{publicInternetExplorerDriverdriver;privateFilelogLocation;privateFiletempDirectory;@AfterEachpublicvoidquit(){if(logLocation!=null&&logLocation.exists()){logLocation.delete();}if(tempDirectory!=null&&tempDirectory.exists()){tempDirectory.delete();}driver.quit();}@TestpublicvoidbasicOptionsWin10(){InternetExplorerOptionsoptions=newInternetExplorerOptions();options.attachToEdgeChrome();options.withEdgeExecutablePath(getEdgeLocation());driver=newInternetExplorerDriver(options);}@TestpublicvoidbasicOptionsWin11(){InternetExplorerOptionsoptions=newInternetExplorerOptions();driver=newInternetExplorerDriver(options);}@TestpublicvoidlogsToFile()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogFile(getLogLocation()).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsToConsole()throwsIOException{System.setOut(newPrintStream(getLogLocation()));InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogOutput(System.out).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Started InternetExplorerDriver server"));}@TestpublicvoidlogsWithLevel()throwsIOException{System.setProperty(InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY,getLogLocation().getAbsolutePath());InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withLogLevel(InternetExplorerDriverLogLevel.WARN).build();driver=newInternetExplorerDriver(service);StringfileContent=newString(Files.readAllBytes(getLogLocation().toPath()));Assertions.assertTrue(fileContent.contains("Invalid capability setting: timeouts is type null"));}@TestpublicvoidsupportingFilesLocation()throwsIOException{InternetExplorerDriverServiceservice=newInternetExplorerDriverService.Builder().withExtractPath(getTempDirectory()).build();driver=newInternetExplorerDriver(service);Assertions.assertTrue(newFile(getTempDirectory()+"/IEDriver.tmp").exists());}privateFilegetLogLocation()throwsIOException{if(logLocation==null||!logLocation.exists()){logLocation=File.createTempFile("iedriver-",".log");}returnlogLocation;}privateFilegetTempDirectory()throwsIOException{if(tempDirectory==null||!tempDirectory.exists()){tempDirectory=Files.createTempDirectory("supporting-").toFile();}returntempDirectory;}privateStringgetEdgeLocation(){returnSystem.getenv("EDGE_BIN");}}
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/InternetExplorerTest.java#L82" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
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
120124
Show full example
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
usingSystem;usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium.IE;usingSeleniumDocs.TestSupport;namespaceSeleniumDocs.Browsers{ [TestClassCustom] [EnabledOnOs("WINDOWS")]publicclassInternetExplorerTest{privateInternetExplorerDriver_driver;privatestring_logLocation;privatestring_tempPath; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}_driver.Quit();} [TestMethod]publicvoidBasicOptionsWin10(){varoptions=newInternetExplorerOptions();options.AttachToEdgeChrome=true;options.EdgeExecutablePath=GetEdgeLocation();_driver=newInternetExplorerDriver(options);} [TestMethod]publicvoidBasicOptionsWin11(){varoptions=newInternetExplorerOptions();_driver=newInternetExplorerDriver(options);} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToFile(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Console.WriteLine("Lines: {0}",lines);Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=InternetExplorerDriverService.CreateDefaultService();//service.LogToConsole = true;_driver=newInternetExplorerDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod]publicvoidLogsLevel(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();service.LoggingLevel=InternetExplorerDriverLogLevel.Warn;_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Invalid capability setting: timeouts is type null")));} [TestMethod]publicvoidSupportingFilesLocation(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LibraryExtractionPath=GetTempDirectory();_driver=newInternetExplorerDriver(service);Assert.IsTrue(File.Exists(GetTempDirectory()+"/IEDriver.tmp"));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath==null||!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatestringGetEdgeLocation(){returnEnvironment.GetEnvironmentVariable("EDGE_BIN");}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
importosimportsubprocessimportsysimportpytestfromseleniumimportwebdriver@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win10(edge_bin):options=webdriver.IeOptions()options.attach_to_edge_chrome=Trueoptions.edge_executable_path=edge_bindriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_basic_options_win11():options=webdriver.IeOptions()driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_file_upload_timeout():options=webdriver.IeOptions()options.file_upload_timeout=2000driver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ensure_clean_session():options=webdriver.IeOptions()options.ensure_clean_session=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_zoom_level():options=webdriver.IeOptions()options.ignore_zoom_level=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_ignore_protected_mode_settings():options=webdriver.IeOptions()options.ignore_protected_mode_settings=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_silent():service=webdriver.IeService(service_args=["--silent"])driver=webdriver.Ie(service=service)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_cmd_options():options=webdriver.IeOptions()options.add_argument("-private")driver=webdriver.Ie(options=options)driver.quit()# Skipping this as it fails on Windows because the value of registry setting in # HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0' @pytest.mark.skipdeftest_force_create_process_api():options=webdriver.IeOptions()options.force_create_process_api=Truedriver=webdriver.Ie(options=options)driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_file(log_path):service=webdriver.IeService(log_output=log_path,log_level="INFO")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Starting WebDriver server"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_to_stdout(capfd):service=webdriver.IeService(log_output=subprocess.STDOUT)driver=webdriver.Ie(service=service)out,err=capfd.readouterr()assert"Started InternetExplorerDriver server"inoutdriver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_log_level(log_path):service=webdriver.IeService(log_output=log_path,log_level="WARN")driver=webdriver.Ie(service=service)withopen(log_path,"r")asfp:assert"Started InternetExplorerDriver server (32-bit)"infp.readline()driver.quit()@pytest.mark.skipif(sys.platform!="win32",reason="requires Windows")deftest_supporting_files(temp_dir):service=webdriver.IeService(service_args=["–extract-path="+temp_dir])driver=webdriver.Ie(service=service)driver.quit()
usingSystem;usingSystem.IO;usingSystem.Linq;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium.IE;usingSeleniumDocs.TestSupport;namespaceSeleniumDocs.Browsers{ [TestClassCustom] [EnabledOnOs("WINDOWS")]publicclassInternetExplorerTest{privateInternetExplorerDriver_driver;privatestring_logLocation;privatestring_tempPath; [TestCleanup]publicvoidCleanup(){if(_logLocation!=null&&File.Exists(_logLocation)){File.Delete(_logLocation);}if(_tempPath!=null&&File.Exists(_tempPath)){File.Delete(_tempPath);}_driver.Quit();} [TestMethod]publicvoidBasicOptionsWin10(){varoptions=newInternetExplorerOptions();options.AttachToEdgeChrome=true;options.EdgeExecutablePath=GetEdgeLocation();_driver=newInternetExplorerDriver(options);} [TestMethod]publicvoidBasicOptionsWin11(){varoptions=newInternetExplorerOptions();_driver=newInternetExplorerDriver(options);} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToFile(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Console.WriteLine("Lines: {0}",lines);Assert.IsTrue(lines.Contains("Started InternetExplorerDriver server"));} [TestMethod] [Ignore("Not implemented")]publicvoidLogsToConsole(){varstringWriter=newStringWriter();varoriginalOutput=Console.Out;Console.SetOut(stringWriter);varservice=InternetExplorerDriverService.CreateDefaultService();//service.LogToConsole = true;_driver=newInternetExplorerDriver(service);Assert.IsTrue(stringWriter.ToString().Contains("geckodriver INFO Listening on"));Console.SetOut(originalOutput);stringWriter.Dispose();} [TestMethod]publicvoidLogsLevel(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LogFile=GetLogLocation();service.LoggingLevel=InternetExplorerDriverLogLevel.Warn;_driver=newInternetExplorerDriver(service);_driver.Quit();// Close the Service log file before readingvarlines=File.ReadLines(GetLogLocation());Assert.IsNotNull(lines.FirstOrDefault(line=>line.Contains("Invalid capability setting: timeouts is type null")));} [TestMethod]publicvoidSupportingFilesLocation(){varservice=InternetExplorerDriverService.CreateDefaultService();service.LibraryExtractionPath=GetTempDirectory();_driver=newInternetExplorerDriver(service);Assert.IsTrue(File.Exists(GetTempDirectory()+"/IEDriver.tmp"));}privatestringGetLogLocation(){if(_logLocation==null||!File.Exists(_logLocation)){_logLocation=Path.GetTempFileName();}return_logLocation;}privatestringGetTempDirectory(){if(_tempPath==null||!File.Exists(_tempPath)){_tempPath=Path.GetTempPath();}return_tempPath;}privatestringGetEdgeLocation(){returnEnvironment.GetEnvironmentVariable("EDGE_BIN");}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Internet Explorer',exclusive:{platform::windows}dodescribe'Options'dolet(:edge_location){ENV.fetch('EDGE_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}beforedo@options=Selenium::WebDriver::IE::Options.new@options.attach_to_edge_chrome=true@options.edge_executable_path=edge_locationendit'basic options Win10'dooptions=Selenium::WebDriver::IE::Options.newoptions.attach_to_edge_chrome=trueoptions.edge_executable_path=edge_location@driver=Selenium::WebDriver.for:ie,options:optionsendit'basic options Win11'dooptions=Selenium::WebDriver::Options.ie@driver=Selenium::WebDriver.for:ie,options:optionsendit'sets the file upload dialog timeout'do@options.file_upload_dialog_timeout=2000driver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ensures a clean session'do@options.ensure_clean_session=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the zoom setting'do@options.ignore_zoom_level=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'ignores the protected mode settings'do@options.ignore_protected_mode_settings=truedriver=Selenium::WebDriver.for(:ie,options:@options)driver.quitendit'adds the silent option',skip:'This capability will be added on the release 4.22.0'do@options.silent=trueexpect(@options.silent).tobe_truthyendit'sets the command line options'do@options.add_argument('-k')Selenium::WebDriver.for(:ie,options:@options)endit'launches ie with the create process api',skip:'When using with IE 8 or higher, it needs a registry value'do@options.force_create_process_api=trueSelenium::WebDriver.for(:ie,options:@options)expect(@options.instance_variable_get(:@options)['force_create_process_api']).toeq({force_create_process_api:true})endenddescribe'Service'dolet(:file_name){Tempfile.new('iedriver').path}let(:root_directory){Dir.mktmpdir}afterdoFileUtils.rm_f(file_name)FileUtils.remove_entryroot_directoryendit'logs to file'doservice=Selenium::WebDriver::Service.ieservice.log=file_name@driver=Selenium::WebDriver.for:ie,service:serviceexpect(File.readlines(file_name).first).toinclude('Started InternetExplorerDriver server')endit'logs to console'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutexpect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Started InternetExplorerDriver server/).to_stdout_from_any_processendit'sets log level'doservice=Selenium::WebDriver::Service.ieservice.log=$stdoutservice.args<<'-log-level=WARN'expect{@driver=Selenium::WebDriver.for:ie,service:service}.tooutput(/Invalid capability setting: timeouts is type null/).to_stdout_from_any_processendit'sets location for supporting files'doservice=Selenium::WebDriver::Service.ieservice.args<<"–extract-path=#{root_directory}"@driver=Selenium::WebDriver.for:ie,service:serviceendendend
Estas capacidades e características são específicas ao navegador Apple Safari.
Ao invés dos drivers para Chromium e Firefox, o safaridriver faz parte to sistema Operativo.
Para activar a automação no Safari, execute o seguinte comando no terminal:
safaridriver --enable
Opções
Capacidades comuns a todos os navegadores estão descritas na página Opções.
Capacidades únicas ao Safari podem ser encontradas na página da Apple WebDriver para Safari
Este é um exemplo de como iniciar uma sessão Safari com um conjunto de opções básicas::
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Safari',exclusive:{platform::macosx}dodescribe'Options'doit'basic options'dooptions=Selenium::WebDriver::Options.safari@driver=Selenium::WebDriver.for:safari,options:optionsendenddescribe'Service'dolet(:directory){"#{Dir.home}/Library/Logs/com.apple.WebDriver/*"}it'enables logs'dooriginal_count=Dir[directory].lengthservice=Selenium::WebDriver::Service.safariservice.args<<'--diagnose'@driver=Selenium::WebDriver.for:safari,service:serviceexpect(Dir[directory].length-original_count).toeq1endit'does not set log output'doservice=Selenium::WebDriver::Service.safariexpect{service.log=$stdout}.toraise_error(Selenium::WebDriver::Error::WebDriverError,/Safari Service does not support setting log output/)endendendRSpec.describe'Safari Technology Preview',skip:"This test is being skipped as GitHub Actions have no support for Safari Technology Preview"doit'sets the technology preview'doSelenium::WebDriver::Safari.technology_preview!local_driver=Selenium::WebDriver.for:safariexpect(local_driver.capabilities.browser_name).toeq'Safari Technology Preview'endend
constsafari=require('selenium-webdriver/safari');const{Browser,Builder}=require("selenium-webdriver");constoptions=newsafari.Options();constprocess=require('node:process');describe('Should be able to Test Command line arguments',function(){(process.platform==='darwin'?it:it.skip)('headless',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.SAFARI).setSafariOptions(options).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
Se pretende automatizar Safari em iOS, deve olhar para o Projecto Appium.
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/.
<div class="text-end pb-2 mt-2">
<a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full/examples/java/src/test/java/dev/selenium/browsers/SafariTest.java#L31" target="_blank">
<i class="fas fa-external-link-alt pl-2"></i>
<strong>View full example on GitHub</strong>
</a>
</div>
Note: Java also allows setting console output by System Property; Property key: SafariDriverService.SAFARI_DRIVER_LOGGING Property value: "true" or "false"
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Safari',exclusive:{platform::macosx}dodescribe'Options'doit'basic options'dooptions=Selenium::WebDriver::Options.safari@driver=Selenium::WebDriver.for:safari,options:optionsendenddescribe'Service'dolet(:directory){"#{Dir.home}/Library/Logs/com.apple.WebDriver/*"}it'enables logs'dooriginal_count=Dir[directory].lengthservice=Selenium::WebDriver::Service.safariservice.args<<'--diagnose'@driver=Selenium::WebDriver.for:safari,service:serviceexpect(Dir[directory].length-original_count).toeq1endit'does not set log output'doservice=Selenium::WebDriver::Service.safariexpect{service.log=$stdout}.toraise_error(Selenium::WebDriver::Error::WebDriverError,/Safari Service does not support setting log output/)endendendRSpec.describe'Safari Technology Preview',skip:"This test is being skipped as GitHub Actions have no support for Safari Technology Preview"doit'sets the technology preview'doSelenium::WebDriver::Safari.technology_preview!local_driver=Selenium::WebDriver.for:safariexpect(local_driver.capabilities.browser_name).toeq'Safari Technology Preview'endend
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Safari',exclusive:{platform::macosx}dodescribe'Options'doit'basic options'dooptions=Selenium::WebDriver::Options.safari@driver=Selenium::WebDriver.for:safari,options:optionsendenddescribe'Service'dolet(:directory){"#{Dir.home}/Library/Logs/com.apple.WebDriver/*"}it'enables logs'dooriginal_count=Dir[directory].lengthservice=Selenium::WebDriver::Service.safariservice.args<<'--diagnose'@driver=Selenium::WebDriver.for:safari,service:serviceexpect(Dir[directory].length-original_count).toeq1endit'does not set log output'doservice=Selenium::WebDriver::Service.safariexpect{service.log=$stdout}.toraise_error(Selenium::WebDriver::Error::WebDriverError,/Safari Service does not support setting log output/)endendendRSpec.describe'Safari Technology Preview',skip:"This test is being skipped as GitHub Actions have no support for Safari Technology Preview"doit'sets the technology preview'doSelenium::WebDriver::Safari.technology_preview!local_driver=Selenium::WebDriver.for:safariexpect(local_driver.capabilities.browser_name).toeq'Safari Technology Preview'endend