O WebDriver manipula um navegador nativamente, como um usuário faria, seja localmente
ou em uma máquina remota usando o servidor Selenium,
marca um salto em termos de automação do navegador.
Selenium WebDriver refere-se a ambas as ligações de linguagem
e as implementações do código de controle do navegador individual.
Isso é comumente referido como apenas WebDriver.
WebDriver é projetado como uma interface de programação simples e mais concisa.
WebDriver é uma API compacta orientada a objetos.
Ele manipula o navegador de forma eficaz.
1 - Começando
Se você é novo no Selenium, nós temos alguns recursos que podem te ajudar a se atualizar imediatamente.
Selenium suporta automação de todos os principais navegadores do mercado
por meio do uso do WebDriver.
WebDriver é uma API e protocolo que define uma interface de linguagem neutra
para controlar o comportamento dos navegadores da web.
Cada navegador é apoiado por uma implementação WebDriver específica, chamada de driver.
O driver é o componente responsável por delegar ao navegador,
e lida com a comunicação de e para o Selenium e o navegador.
Essa separação é parte de um esforço consciente para que os fornecedores de navegadores
assumam a responsabilidade pela implementação de seus navegadores.
Selenium faz uso desses drivers de terceiros sempre que possível,
mas também fornece seus próprios drivers mantidos pelo projeto
para os casos em que isso não é uma realidade.
A estrutura do Selenium une todas essas peças
por meio de uma interface voltada para o usuário que permite aos diferentes back-ends de navegador
serem usados de forma transparente,
permitindo a automação entre navegadores e plataformas cruzadas.
Selenium setup is quite different from the setup of other commercial tools.
Before you can start writing Selenium code, you have to
install the language bindings libraries for your language of choice, the browser you
want to use, and the driver for that browser.
Follow the links below to get up and going with Selenium WebDriver.
If you wish to start with a low-code/record and playback tool, please check
Selenium IDE
Once you get things working, if you want to scale up your tests, check out the
Selenium Grid.
1.1 - Instalando bibliotecas do Selenium
Configurando a biblioteca Selenium para sua linguagem de programação favorita.
Primeiro você precisa instalar as bibliotecas Selenium para seu projeto de automação.
O processo de instalação de bibliotecas depende da linguagem que você escolher usar.
Outras observações para usar o Visual Studio Code (vscode) e C#
Instale a versão compatível do .NET SDK conforme a seção acima.
Instale também as extensões do vscode (Ctrl-Shift-X) para C# e NuGet.
Siga as instruções aqui para criar e rodar o seu projeto de “Hello World” no console usando C#.
Você também pode criar um projeto inicial do NUnit usando a linha de comando dotnet new NUnit.
Certifique-se de que o arquivo %appdata%\NuGet\nuget.config esteja configurado corretamente, pois alguns desenvolvedores relataram que ele estará vazio devido a alguns problemas.
Se o nuget.config estiver vazio ou não estiver configurado corretamente, as compilações .NET falharão para projetos que estiverem usando Selenium.
Adicione a seguinte seção ao arquivo nuget.config se esse estiver vazio:
Para mais informações sobre nuget.configclique aqui.
Você pode ter que customizar nuget.config para atender às suas necessidades.
Agora, volte para o vscode, aperte Ctrl-Shift-P, e digite “NuGet Add Package”, e adicione os pacotes necessários para
o Selenium como o Selenium.WebDriver.
Aperte Enter e selecione a versão.
Agora você pode usar os exemplos da documentação relacionados ao C# com o vscode.
Você pode ver a minima versão suportada do Ruby para cada versão do Selenium em
rubygems.org
O Selenium pode ser instalado de duas formas diferentes.
Instruções passo a passo para programar um script Selenium
Assim que você tiver o Selenium instalado,
você estará pronto para programar códigos Selenium.
Oito Componentes Básicos
Tudo que o Selenium faz é enviar comandos ao navegador de internet para fazer algo ou solicitar informações dele.
A maior parte do que você irá fazer com o Selenium é uma combinação desses comandos básicos.
Click on the link to “View full example on GitHub” to see the code in context.
1. Iniciando uma sessão
Para ter mais detalhes sobre como iniciar uma sessão, leia nossa documentação em driver sessions
3. Solicitando informação do navegador de internet
Existem diversos tipos de informação sobre o navegador de internet que você
pode solicitar, incluindo window handles, tamanho / posição do navegador, cookies, alertas e etc.
Sincronizar o código ao estado atual do navegador é um dos maiores
desafios
quando se trabalha com o Selenium, fazer isso de maneira bem feita é um tópico avançado.
Essencialmente, você quer ter certeza absoluta de que o elemento está na página antes de tentar localizá-lo
e o elemento está em um estado interativo antes de você tentar interagir com ele.
Uma espera implícita raramente é a melhor solução, mas é a mais fácil de demonstrar aqui, então
vamos usá-la como um substituto.
A maioria dos comandos na maior parte das sessões do Selenium são relacionados a elementos e você não pode
interagir
com um sem o primeiro encontrando um elemento
# Running Selenium Java Tests
The following steps will guide you on how to
run Selenium Java tests using a repository
of `SeleniumHQ/seleniumhq.github.io` examples.
## Initial Setup
### Prerequisites
Ensure that Java Development Kit (JDK) and Maven
are installed on your system. If they are not installed,
you will need to download and install them. You can
find detailed installation guides for both on their
respective official sites.
### Clone the repository
First, we need to get the Selenium Java examples
on your local machine. This can be done by
cloning the `SeleniumHQ/seleniumhq.github.io` Git repository.
Run the following command in your terminal:
```bash
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```## Navigate to the java directory
After cloning the repository, navigate into the
directory where the Selenium Java examples are
located. Run the following command:
```bash
cd seleniumhq.github.io/examples/java
```## Running the Tests
### Install dependencies
Before running the tests, we need to install all
necessary dependencies. Maven, a software
project management tool, can do this for us.
Run the following command:
```bash
mvn test-compile
```### Run all tests
To verify if everything is installed correctly and
functioning properly, we should run all
available tests. This can be done with the following command:
```bash
mvn test```Please be patient! If this is your first time running these tests,
it might take a while to download and verify all necessary browser drivers.
## Execute a specific example
To run a specific Selenium Java example, use the following command:
```bash
mvn exec:java -D"exec.mainClass"="dev.selenium.getting_started.FirstScript" -D"exec.classpathScope"=test```Make sure to replace `dev.selenium.getting_started.FirstScript` with the path and name of the example you want to run.
# Running tests from Selenium Python examples
#### 1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```#### 2. Navigate to `python` directory
```
cd seleniumhq.github.io/examples/python
```#### 3. Create a virtual environment
- On Windows:
```
py -m venv venv
venv\Scripts\activate
```- On Linux/Mac:
```
python3 -m venv venv
source venv/bin/activate
```#### 4. Install dependencies:
```
pip install -r requirements.txt
```> for help, see: https://packaging.python.org/en/latest/tutorials/installing-packages
#### 5. Run tests
- Run all tests with the default Python interpreter:
```
pytest
```- Run all tests with every installed/supported Python interpreter:
```
tox
```> Please have some patience - If you are doing it for the first time, it will take a little while to download the browser drivers
- Run a specific example:
```
pytest path/to/test_script.py
```> Make sure to replace `path/to/test_script.py` with the path and name of the example you want to run
# Running all tests from Selenium ruby example
Follow these steps to run all test example from selenium ruby
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```2. Navigate to `ruby` directory
```
cd seleniumhq.github.io/examples/ruby
```3. Install dependencies using bundler
```
bundler install
```4. Run all tests
```
bundle exec rspec
```> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a ruby script
Use this command to run a ruby script and follow the first script example
```
ruby example_script.rb
```
# Running all tests from Selenium javascript example
Follow these steps to run all test example from selenium javascript
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```2. Navigate to `javascript` directory
```
cd seleniumhq.github.io/examples/javascript
```3. Install dependencies using node
```
npm install
```4. Run all all tests
```
npm test
```> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a javascript test
Use this command to run a JavaScript and follow the first script example
```
node example_script.spec.js
```
Most Selenium users execute many sessions and need to organize them to minimize duplication and keep the code
more maintainable. Read on to learn about how to put this code into context for your use case with
Using Selenium.
1.3 - Organizando e executando o código Selenium
Escalonamento da execução do Selenium com um IDE e uma biblioteca do Test Runner
Se quiser executar mais do que um punhado de scripts pontuais, precisa de
ser capaz de organizar e trabalhar com seu código. Esta página deve dar a você
ideias de como fazer coisas produtivas com seu código Selenium.
Usos comuns
A maioria das pessoas usa o Selenium para executar testes automatizados para aplicações web,
mas o Selenium suporta qualquer caso de uso de automação de navegador.
Tarefas Repetitivas
Talvez seja necessário fazer login em um site e baixar algo ou enviar um formulário.
Você pode criar um script Selenium para ser executado com um serviço em horários pré-definidos.
Web Scrapping
Está a tentar recolher dados de um site que não tem uma API? O Selenium
permitirá que você faça isso, mas certifique-se de estar familiarizado com os termos de serviço do site
termos de serviço do site, pois alguns sites não permitem isso e outros até bloqueiam o Selenium.
Testes
Executar o Selenium para testes requer fazer asserções sobre as ações tomadas pelo Selenium.
Então uma boa biblioteca de asserções é necessária. Características adicionais para prover estrutura para testes
requerem o uso de Executador de teste.
IDEs
Independentemente de como você usa o código do Selenium,
não será muito eficaz escrevendo ou executando-o sem um bom
ambiente de desenvolvimento integrado. Aqui estão algumas opções comuns…
Mesmo que não esteja a usar o Selenium para testes, se tiver casos de uso avançado, pode fazer
sentido usar um executor de testes para organizar melhor seu código. Ser capaz de usar hooks antes/depois
e executar coisas em grupos ou em paralelo pode ser muito útil.
Escolhendo
Há muitos executores de teste diferentes disponíveis.
Todos os exemplos de código nesta documentação podem ser encontrados em (ou estão sendo movidos para) nossos diretórios
que usam test runners e são executados a cada lançamento para garantir que todo o código esteja correto e atualizado.
Aqui está uma lista de executores de teste com links. O primeiro item é o que é usado por este repositório e o que
que será usado para todos os exemplos nesta página.
JUnit - Uma estrutura de teste amplamente utilizada para testes Selenium baseados em Java.
TestNG - Oferece recursos extras, como execução de testes paralelos e testes parametrizados.
pytest -Uma escolha preferida por muitos, graças à sua simplicidade e aos seus poderosos plugins.
unittest - A estrutura de testes da biblioteca padrão do Python.
NUnit - Um popular framework de teste unitário para .NET.
MS Test - O Framework de testes unitários da Microsoft.
RSpec - A biblioteca de testes mais utilizada para executar testes Selenium em Ruby.
Minitest - Um framework de testes leve que vem com a biblioteca padrão do Ruby.
Jest - Principalmente conhecido como um framework de teste para React, também pode ser utilizado para testes Selenium.
Mocha - A biblioteca JS mais comum para executar testes Selenium.
Kotest - Uma estrutura de testes flexível e abrangente, projetada especificamente para Kotlin.
JUnit5 - A estrutura de testes padrão do Java, totalmente compatível com Kotlin.
Instalando
Isto é muito semelhante ao que foi requerido em Install a Selenium Library.
Este código está apenas a mostrar exemplos do que está a ser usado no nosso projeto de Exemplos de Documentação.
Maven
Gradle
Para usá-lo em um projeto, adicione-o ao arquivo requirements.txt:
in the project’s csproj especifique a dependência como PackageReference em ItemGroup:
Add to project’s gemfile
In your project’s package.json, adicionar requisito às dependências:
# frozen_string_literal: truerequire'selenium-webdriver'require'selenium/webdriver/support/guards'RSpec.configuredo|config|# Enable flags like --only-failures and --next-failureconfig.example_status_persistence_file_path='.rspec_status'# Disable RSpec exposing methods globally on `Module` and `main`config.disable_monkey_patching!Dir.mktmpdir('tmp')config.example_status_persistence_file_path='tmp/examples.txt'config.expect_with:rspecdo|c|c.syntax=:expectendconfig.beforedo|example|bug_tracker='https://github.com/SeleniumHQ/seleniumhq.github.io/issues'guards=Selenium::WebDriver::Support::Guards.new(example,bug_tracker:bug_tracker)guards.add_condition(:platform,Selenium::WebDriver::Platform.os)guards.add_condition(:ci,Selenium::WebDriver::Platform.ci)results=guards.dispositionsend(*results)ifresultsendconfig.after{@driver&.quit}defstart_sessionoptions=Selenium::WebDriver::Chrome::Options.newoptions.add_argument('disable-search-engine-choice-screen')options.add_argument('--no-sandbox')@driver=Selenium::WebDriver.for(:chrome,options:options)enddefstart_bidi_sessionoptions=Selenium::WebDriver::Chrome::Options.new(web_socket_url:true)@driver=Selenium::WebDriver.for:chrome,options:optionsenddefstart_firefoxoptions=Selenium::WebDriver::Options.firefox(timeouts:{implicit:1500})@driver=Selenium::WebDriver.for:firefox,options:optionsendend
# Running tests from Selenium Python examples
#### 1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```#### 2. Navigate to `python` directory
```
cd seleniumhq.github.io/examples/python
```#### 3. Create a virtual environment
- On Windows:
```
py -m venv venv
venv\Scripts\activate
```- On Linux/Mac:
```
python3 -m venv venv
source venv/bin/activate
```#### 4. Install dependencies:
```
pip install -r requirements.txt
```> for help, see: https://packaging.python.org/en/latest/tutorials/installing-packages
#### 5. Run tests
- Run all tests with the default Python interpreter:
```
pytest
```- Run all tests with every installed/supported Python interpreter:
```
tox
```> Please have some patience - If you are doing it for the first time, it will take a little while to download the browser drivers
- Run a specific example:
```
pytest path/to/test_script.py
```> Make sure to replace `path/to/test_script.py` with the path and name of the example you want to run
# Running all tests from Selenium ruby example
Follow these steps to run all test example from selenium ruby
1. Clone this repository
```
git clone https://github.com/SeleniumHQ/seleniumhq.github.io.git
```2. Navigate to `ruby` directory
```
cd seleniumhq.github.io/examples/ruby
```3. Install dependencies using bundler
```
bundler install
```4. Run all tests
```
bundle exec rspec
```> Please keep some patience - If you are doing it for the first time, it will take a little while to verify and download the browser drivers
# Execute a ruby script
Use this command to run a ruby script and follow the first script example
```
ruby example_script.rb
```
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()defget_default_chrome_options():options=webdriver.ChromeOptions()options.add_argument("--no-sandbox")returnoptions
usingSystem;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Net;usingSystem.Net.Http;usingSystem.Net.Sockets;usingSystem.Runtime.InteropServices;usingSystem.Threading.Tasks;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceSeleniumDocs{publicclassBaseTest{protectedIWebDriverdriver;protectedUriGridUrl;privateProcess_webserverProcess;privateconststringServerJarName="selenium-server-4.33.0.jar";privatestaticreadonlystringBaseDirectory=AppContext.BaseDirectory;privateconststringRelativePathToGrid="../../../../../";privatereadonlystring_examplesDirectory=Path.GetFullPath(Path.Combine(BaseDirectory,RelativePathToGrid)); [TestCleanup]publicvoidCleanup(){driver?.Quit();if(_webserverProcess!=null){StopServer();}}protectedvoidStartDriver(stringbrowserVersion=null){ChromeOptionsoptions=newChromeOptions();if(browserVersion!=null){options.BrowserVersion=browserVersion;stringuserDataDir=System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetRandomFileName());System.IO.Directory.CreateDirectory(userDataDir);options.AddArgument($"--user-data-dir={userDataDir}");options.AddArgument("--no-sandbox");options.AddArgument("--disable-dev-shm-usage");}driver=newChromeDriver(options);}protectedasyncTaskStartServer(){if(_webserverProcess==null||_webserverProcess.HasExited){_webserverProcess=newProcess();_webserverProcess.StartInfo.FileName=RuntimeInformation.IsOSPlatform(OSPlatform.Windows)?"java.exe":"java";stringport=GetFreeTcpPort().ToString();GridUrl=newUri("http://localhost:"+port+"/wd/hub");_webserverProcess.StartInfo.Arguments=" -jar "+ServerJarName+" standalone --port "+port+" --selenium-manager true --enable-managed-downloads true";_webserverProcess.StartInfo.WorkingDirectory=_examplesDirectory;_webserverProcess.Start();awaitEnsureGridIsRunningAsync();}}privatevoidStopServer(){if(_webserverProcess!=null&&!_webserverProcess.HasExited){_webserverProcess.Kill();_webserverProcess.Dispose();_webserverProcess=null;}}privatestaticintGetFreeTcpPort(){TcpListenerl=newTcpListener(IPAddress.Loopback,0);l.Start();intport=((IPEndPoint)l.LocalEndpoint).Port;l.Stop();returnport;}privateasyncTaskEnsureGridIsRunningAsync(){DateTimetimeout=DateTime.Now.Add(TimeSpan.FromSeconds(30));boolisRunning=false;HttpClientclient=newHttpClient();while(!isRunning&&DateTime.Now<timeout){try{HttpResponseMessageresponse=awaitclient.GetAsync(GridUrl+"/status");if(response.IsSuccessStatusCode){isRunning=true;}else{awaitTask.Delay(500);}}catch(HttpRequestException){awaitTask.Delay(500);}}if(!isRunning){thrownewTimeoutException("Could not confirm the remote selenium server is running within 30 seconds");}}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Chrome'dodescribe'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
The primary unique argument for starting a remote driver includes information about where to execute the code.
Read the details in the Remote Driver Section
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
Esses recursos são compartilhados por todos os navegadores.
Page being translated from English to Portuguese.
Do you speak Portuguese? Help us to translate
it by sending us pull requests!
No Selenium 3, os recursos foram definidos em uma sessão usando classes de recursos desejados.
A partir do Selenium 4, você deve usar as classes de opções do navegador.
Para sessões remotas de driver, uma instância de opções do navegador é necessária, pois determina qual navegador será usado.
Essas opções são descritas na especificação w3c para Capabilities.
Cada navegador tem custom options que podem ser definidas além das definidas na especificação.
browserName
Esta capacidade é usada para definir o browserName para uma determinada sessão.
Se o navegador especificado não estiver instalado no
extremidade remota, a criação da sessão falhará.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
Esta capacidade é opcional, é usada para
defina a versão do navegador disponível na extremidade remota.
Por exemplo, se solicitar o Chrome versão 75 em um sistema que
tiver apenas 80 instalados, a criação da sessão falhará.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
Três tipos de estratégias de carregamento de página estão disponíveis.
A estratégia de carregamento da página consulta o
document.readyState
conforme descrito na tabela abaixo:
Estratégia
Estado pronto
Notas
normal
completo
Usado por padrão, aguarda o download de todos os recursos
ansioso
interativo
O acesso DOM está pronto, mas outros recursos como imagens ainda podem estar carregando
nenhum
Qualquer
Não bloqueia o WebDriver
A propriedade document.readyState de um documento descreve o estado de carregamento do documento atual.
Ao navegar para uma nova página via URL, por padrão, o WebDriver irá adiar a conclusão de uma navegação
(por exemplo, driver.navigate().get()) até que o estado pronto do documento seja concluído. isso não
significa necessariamente que a página terminou de carregar, especialmente para sites como Single Page Applications
que usam JavaScript para carregar conteúdo dinamicamente depois que o estado Pronto retorna completo. Observe também
que esse comportamento não se aplica à navegação resultante de clicar em um elemento ou enviar um formulário.
Se uma página demorar muito para carregar como resultado do download de ativos (por exemplo, imagens, css, js)
que não são importantes para a automação, você pode mudar do parâmetro padrão de normal para
eager ou none para acelerar a sessão. Esse valor se aplica a toda a sessão, portanto, certifique-se
que sua waiting strategy é suficiente para minimizar
descamação.
normal (default)
WebDriver waits until the load
event fire is returned.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options()describe('Page loading strategies',function(){it('Navigate using eager page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('eager')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using none page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('none')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using normal page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('normal')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to accept certs',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setAcceptInsecureCerts(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options()describe('Page loading strategies',function(){it('Navigate using eager page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('eager')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using none page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('none')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using normal page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('normal')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to accept certs',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setAcceptInsecureCerts(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options()describe('Page loading strategies',function(){it('Navigate using eager page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('eager')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using none page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('none')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using normal page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('normal')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to accept certs',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setAcceptInsecureCerts(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
This capability checks whether an expired (or)
invalid TLS Certificate is used while navigating
during a session.
If the capability is set to false, an
insecure certificate error
will be returned as navigation encounters any domain
certificate problems. If set to true, invalid certificate will be
trusted by the browser.
All self-signed certificates will be trusted by this capability by default.
Once set, acceptInsecureCerts capability will have an
effect for the entire session.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
constChrome=require('selenium-webdriver/chrome');const{Browser,Builder}=require("selenium-webdriver");constoptions=newChrome.Options()describe('Page loading strategies',function(){it('Navigate using eager page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('eager')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using none page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('none')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Navigate using normal page loading strategy',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setPageLoadStrategy('normal')).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});it('Should be able to accept certs',asyncfunction(){letdriver=newBuilder().forBrowser(Browser.CHROME).setChromeOptions(options.setAcceptInsecureCerts(true)).build();awaitdriver.get('https://www.selenium.dev/selenium/web/blank.html');awaitdriver.quit();});});
A WebDriver session is imposed with a certain session timeout
interval, during which the user can control the behaviour
of executing scripts or retrieving information from the browser.
Each session timeout is configured with
combination of different timeouts as described below:
Script Timeout
Specifies when to interrupt an executing script in
a current browsing context. The default timeout 30,000
is imposed when a new session is created by WebDriver.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
Specifies the time interval in which web page
needs to be loaded in a current browsing context.
The default timeout 300,000 is imposed when a
new session is created by WebDriver. If page load limits
a given/default time frame, the script will be stopped by
TimeoutException.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
This specifies the time to wait for the
implicit element location strategy when
locating elements. The default timeout 0
is imposed when a new session is created by WebDriver.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
Specifies the state of current session’s user prompt handler.
Defaults to dismiss and notify state
User Prompt Handler
This defines what action must take when a
user prompt encounters at the remote-end. This is defined by
unhandledPromptBehavior capability and has the following states:
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
This new capability indicates if strict interactability checks
should be applied to input type=file elements. As strict interactability
checks are off by default, there is a change in behaviour
when using Element Send Keys with hidden file upload controls.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.time.Duration;importjava.time.temporal.ChronoUnit;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.Assertions;importorg.openqa.selenium.PageLoadStrategy;importorg.openqa.selenium.UnexpectedAlertBehaviour;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.CapabilityType;importorg.openqa.selenium.chrome.ChromeDriver;publicclassOptionsTestextendsBaseTest{@TestpublicvoidsetPageLoadStrategyNormal(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyEager(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetPageLoadStrategyNone(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidsetAcceptInsecureCerts(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setAcceptInsecureCerts(true);WebDriverdriver=newChromeDriver(chromeOptions);try{// Navigate to Urldriver.get("https://selenium.dev");}finally{driver.quit();}}@TestpublicvoidgetBrowserName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringname=chromeOptions.getBrowserName();Assertions.assertFalse(name.isEmpty(),"Browser name should not be empty");}@TestpublicvoidsetBrowserVersion(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringversion="latest";chromeOptions.setBrowserVersion(version);Assertions.assertEquals(version,chromeOptions.getBrowserVersion());}@TestpublicvoidsetPlatformName(){ChromeOptionschromeOptions=getDefaultChromeOptions();Stringplatform="OS X 10.6";chromeOptions.setPlatformName(platform);Assertions.assertEquals(platform,chromeOptions.getPlatformName().toString());}@TestpublicvoidsetScriptTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setScriptTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getScriptTimeout();Assertions.assertEquals(timeout,duration,"The script timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetPageLoadTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setPageLoadTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getPageLoadTimeout();Assertions.assertEquals(timeout,duration,"The page load timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetImplicitWaitTimeout(){ChromeOptionschromeOptions=getDefaultChromeOptions();Durationduration=Duration.of(5,ChronoUnit.SECONDS);chromeOptions.setImplicitWaitTimeout(duration);WebDriverdriver=newChromeDriver(chromeOptions);try{Durationtimeout=driver.manage().timeouts().getImplicitWaitTimeout();Assertions.assertEquals(timeout,duration,"The implicit wait timeout should be set to 5 seconds.");}finally{driver.quit();}}@TestpublicvoidsetUnhandledPromptBehaviour(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR);Assertions.assertNotNull(capabilityObject,"Capability UNHANDLED_PROMPT_BEHAVIOUR should not be null.");Assertions.assertEquals(capabilityObject.toString(),UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY.toString());}@TestpublicvoidsetWindowRect(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.SET_WINDOW_RECT);Assertions.assertNotNull(capabilityObject,"Capability SET_WINDOW_RECT should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability SET_WINDOW_RECT should be set to true.");}@TestpublicvoidsetStrictFileInteractability(){ChromeOptionschromeOptions=getDefaultChromeOptions();chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY,true);//verify the capability object is not nullObjectcapabilityObject=chromeOptions.getCapability(CapabilityType.STRICT_FILE_INTERACTABILITY);Assertions.assertNotNull(capabilityObject,"Capability STRICT_FILE_INTERACTABILITY should not be null.");Booleancapability=(Boolean)capabilityObject;Assertions.assertTrue(capability,"The capability STRICT_FILE_INTERACTABILITY should be set to true.");}}
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
A proxy server acts as an intermediary for
requests between a client and a server. In simple,
the traffic flows through the proxy server
on its way to the address you requested and back.
A proxy server for automation scripts
with Selenium could be helpful for:
Capture network traffic
Mock backend calls made by the website
Access the required website under complex network
topologies or strict corporate restrictions/policies.
If you are in a corporate environment, and a
browser fails to connect to a URL, this is most
likely because the environment needs a proxy to be accessed.
Selenium WebDriver provides a way to proxy settings:
fromseleniumimportwebdriverfromselenium.webdriver.common.proxyimportProxyfromselenium.webdriver.common.proxyimportProxyTypedeftest_page_load_strategy_normal():options=get_default_chrome_options()options.page_load_strategy='normal'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_eager():options=get_default_chrome_options()options.page_load_strategy='eager'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_page_load_strategy_none():options=get_default_chrome_options()options.page_load_strategy='none'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_script():options=get_default_chrome_options()options.timeouts={'script':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_page_load():options=get_default_chrome_options()options.timeouts={'pageLoad':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_timeouts_implicit_wait():options=get_default_chrome_options()options.timeouts={'implicit':5000}driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_unhandled_prompt():options=get_default_chrome_options()options.unhandled_prompt_behavior='accept'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_window_rect():options=webdriver.FirefoxOptions()options.set_window_rect=True# Full support in Firefoxdriver=webdriver.Firefox(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_strict_file_interactability():options=get_default_chrome_options()options.strict_file_interactability=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_proxy():options=get_default_chrome_options()options.proxy=Proxy({'proxyType':ProxyType.MANUAL,'httpProxy':'http.proxy:1234'})driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_name():options=get_default_chrome_options()assertoptions.capabilities['browserName']=='chrome'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_set_browser_version():options=get_default_chrome_options()options.browser_version='stable'assertoptions.capabilities['browserVersion']=='stable'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_platform_name():options=get_default_chrome_options()options.platform_name='any'driver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")driver.quit()deftest_accept_insecure_certs():options=get_default_chrome_options()options.accept_insecure_certs=Truedriver=webdriver.Chrome(options=options)driver.get("https://www.selenium.dev/")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'Driver Options'dolet(:chrome_location){driver_finder&&ENV.fetch('CHROME_BIN',nil)}let(:url){'https://www.selenium.dev/selenium/web/'}it'page load strategy normal'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:normaldriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy eager'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:eagerdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'page load strategy none'dooptions=Selenium::WebDriver::Options.chromeoptions.page_load_strategy=:nonedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets remote capabilities',skip:'this is example code that will not execute'dooptions=Selenium::WebDriver::Options.firefoxoptions.platform_name='Windows 10'options.browser_version='latest'cloud_options={}cloud_options[:build]=my_test_buildcloud_options[:name]=my_test_nameoptions.add_option('cloud:options',cloud_options)driver=Selenium::WebDriver.for:remote,capabilities:optionsdriver.get(url)driver.quitendit'accepts untrusted certificates'dooptions=Selenium::WebDriver::Options.chromeoptions.accept_insecure_certs=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets unhandled prompt behavior'dooptions=Selenium::WebDriver::Options.chromeoptions.unhandled_prompt_behavior=:acceptdriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets window rect'dooptions=Selenium::WebDriver::Options.firefoxoptions.set_window_rect=truedriver=Selenium::WebDriver.for:firefox,options:optionsdriver.get(url)driver.quitendit'sets strict file interactability'dooptions=Selenium::WebDriver::Options.chromeoptions.strict_file_interactability=truedriver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the proxy'dooptions=Selenium::WebDriver::Options.chromeoptions.proxy=Selenium::WebDriver::Proxy.new(http:'myproxy.com:8080')driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the implicit timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={implicit:1}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the page load timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={page_load:400_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets the script timeout'dooptions=Selenium::WebDriver::Options.chromeoptions.timeouts={script:40_000}driver=Selenium::WebDriver.for:chrome,options:optionsdriver.get(url)driver.quitendit'sets capabilities in the pre-selenium 4 way',skip:'this is example code that will not execute'docaps=Selenium::WebDriver::Remote::Capabilities.firefoxcaps[:platform]='Windows 10'caps[:version]='92'caps[:build]=my_test_buildcaps[:name]=my_test_namedriver=Selenium::WebDriver.for:remote,url:cloud_url,desired_capabilities:capsdriver.get(url)driver.quitendendend
The Service classes are for managing the starting and stopping of drivers.
They can not be used with a Remote WebDriver session.
Service classes allow you to specify information about the driver,
like location and which port to use.
They also let you specify what arguments get passed
to the command line. Most of the useful arguments are related to logging.
Default Service instance
To start a driver with a default service instance:
Note: If you are using Selenium 4.6 or greater, you shouldn’t need to set a driver location.
If you can not update Selenium or have an advanced use case here is how to specify the driver location:
Logging functionality varies between browsers. Most browsers allow you to
specify location and level of logs. Take a look at the respective browser page:
Page being translated from
English to Portuguese. Do you speak Portuguese? Help us to translate
it by sending us pull requests!
Selenium lets you automate browsers on remote computers if
there is a Selenium Grid running on them. The computer that
executes the code is referred to as the client computer, and the computer with the browser and driver is
referred to as the remote computer or sometimes as an end-node.
To direct Selenium tests to the remote computer, you need to use a Remote WebDriver class
and pass the URL including the port of the grid on that machine. Please see the grid documentation
for all the various ways the grid can be configured.
Basic Example
The driver needs to know where to send commands to and which browser to start on the Remote computer. So an address
and an options instance are both required.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
Uploading a file is more complicated for Remote WebDriver sessions because the file you want to
upload is likely on the computer executing the code, but the driver on the
remote computer is looking for the provided path on its local file system.
The solution is to use a Local File Detector. When one is set, Selenium will bundle
the file, and send it to the remote machine, so the driver can see the reference to it.
Some bindings include a basic local file detector by default, and all of them allow
for a custom file detector.
Java does not include a Local File Detector by default, so you must always add one to do uploads.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
Python adds a local file detector to remote webdriver instances by default, but you can also create your own class.
Chrome, Edge and Firefox each allow you to set the location of the download directory.
When you do this on a remote computer, though, the location is on the remote computer’s local file system.
Selenium allows you to enable downloads to get these files onto the client computer.
Enable Downloads in the Grid
Regardless of the client, when starting the grid in node or standalone mode,
you must add the flag:
--enable-managed-downloads true
Enable Downloads in the Client
The grid uses the se:downloadsEnabled capability to toggle whether to be responsible for managing the browser location.
Each of the bindings have a method in the options class to set this.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
Be aware that Selenium is not waiting for files to finish downloading,
so the list is an immediate snapshot of what file names are currently in the directory for the given session.
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
Each browser has implemented special functionality that is available only to that browser.
Each of the Selenium bindings has implemented a different way to use those features in a Remote Session
Java requires you to use the Augmenter class, which allows it to automatically pull in implementations for
all interfaces that match the capabilities used with the RemoteWebDriver
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
Of interest, using the RemoteWebDriverBuilder automatically augments the driver, so it is a great way
to get all the functionality by default:
packagedev.selenium.drivers;importdev.selenium.BaseTest;importjava.io.File;importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.time.Duration;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.openqa.selenium.By;importorg.openqa.selenium.HasDownloads;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.chromium.HasCasting;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.LocalFileDetector;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.remote.http.ClientConfig;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassRemoteWebDriverTestextendsBaseTest{URLgridUrl;@BeforeEachpublicvoidstartGrid(){gridUrl=startStandaloneGrid();}@TestpublicvoidrunRemote(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);}@Testpublicvoiduploads(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver.get("https://the-internet.herokuapp.com/upload");FileuploadFile=newFile("src/test/resources/selenium-snapshot.png");((RemoteWebDriver)driver).setFileDetector(newLocalFileDetector());WebElementfileInput=driver.findElement(By.cssSelector("input[type=file]"));fileInput.sendKeys(uploadFile.getAbsolutePath());driver.findElement(By.id("file-submit")).click();WebElementfileName=driver.findElement(By.id("uploaded-files"));Assertions.assertEquals("selenium-snapshot.png",fileName.getText());}@Testpublicvoiddownloads()throwsIOException{ChromeOptionsoptions=getDefaultChromeOptions();options.setEnableDownloads(true);driver=newRemoteWebDriver(gridUrl,options);List<String>fileNames=newArrayList<>();fileNames.add("file_1.txt");fileNames.add("file_2.jpg");driver.get("https://www.selenium.dev/selenium/web/downloads/download.html");driver.findElement(By.id("file-1")).click();driver.findElement(By.id("file-2")).click();newWebDriverWait(driver,Duration.ofSeconds(5)).until(d->((HasDownloads)d).getDownloadableFiles().contains("file_2.jpg"));List<String>files=((HasDownloads)driver).getDownloadableFiles();// Sorting them to avoid differences when comparing the filesfileNames.sort(Comparator.naturalOrder());files.sort(Comparator.naturalOrder());Assertions.assertEquals(fileNames,files);StringdownloadableFile=files.get(0);PathtargetDirectory=Files.createTempDirectory("download");((HasDownloads)driver).downloadFile(downloadableFile,targetDirectory);StringfileContent=String.join("",Files.readAllLines(targetDirectory.resolve(downloadableFile)));Assertions.assertEquals("Hello, World!",fileContent);((HasDownloads)driver).deleteDownloadableFiles();Assertions.assertTrue(((HasDownloads)driver).getDownloadableFiles().isEmpty());}@Testpublicvoidaugment(){ChromeOptionsoptions=getDefaultChromeOptions();driver=newRemoteWebDriver(gridUrl,options);driver=newAugmenter().augment(driver);Assertions.assertTrue(driverinstanceofHasCasting);}@TestpublicvoidremoteWebDriverBuilder(){driver=RemoteWebDriver.builder().address(gridUrl).oneOf(getDefaultChromeOptions()).setCapability("ext:options",Map.of("key","value")).config(ClientConfig.defaultConfig()).build();Assertions.assertTrue(driverinstanceofHasCasting);}}
This feature is only available for Java client binding (Beta onwards). The Remote WebDriver client sends requests to the Selenium Grid server, which passes them to the WebDriver. Tracing should be enabled at the server and client-side to trace the HTTP requests end-to-end. Both ends should have a trace exporter setup pointing to the visualization framework.
By default, tracing is enabled for both client and server.
To set up the visualization framework Jaeger UI and Selenium Grid 4, please refer to Tracing Setup for the desired version.
For client-side setup, follow the steps below.
Add the required dependencies
Installation of external libraries for tracing exporter can be done using Maven.
Add the opentelemetry-exporter-jaeger and grpc-netty dependency in your project pom.xml:
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);options.addArguments("--disable-features=DisableLoadExtensionCommandLineSwitch");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
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(){stringuserDataDir=System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetRandomFileName());System.IO.Directory.CreateDirectory(userDataDir);varoptions=newChromeOptions();options.AddArgument($"--user-data-dir={userDataDir}");options.AddArgument("--no-sandbox");options.AddArgument("--disable-dev-shm-usage");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);options.AddArgument("--disable-features=DisableLoadExtensionCommandLineSwitch");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.Debugdriver=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'douser_data_dir=Dir.mktmpdir('chrome-profile-')options=Selenium::WebDriver::Options.chromeoptions.add_argument("--user-data-dir=#{user_data_dir}")options.add_argument('--no-sandbox')options.add_argument('--disable-dev-shm-usage')options.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)options.add_argument('--disable-features=DisableLoadExtensionCommandLineSwitch')@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.