This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

O Projeto Selenium de Automação de Navegadores

Selenium é um projeto que abrange uma variedade de ferramentas e bibliotecas que permitem e suportam a automação de navegadores da web.

Ele fornece extensões para emular a interação do usuário com os navegadores, um servidor de distribuição para escalonar a alocação do navegador, e a infraestrutura para implementações da Especificação W3C WebDriver que permite escrever código intercambiável para todos os principais navegadores da web.

Este projeto é possível graças a colaboradores voluntários que dedicam milhares de horas de seu próprio tempo, e disponibilizaram o código-fonte disponível gratuitamente para qualquer um usar, aproveitar e melhorar.

Selenium reúne criadores de navegadores, engenheiros e entusiastas para promover uma discussão aberta sobre a automação da plataforma da web. O projeto organiza uma conferência anual para ensinar e nutrir a comunidade.

No núcleo do Selenium está WebDriver, uma interface para escrever conjuntos de instruções que podem ser executados alternadamente em muitos navegadores. Aqui está uma das instruções mais simples que você pode fazer:

package dev.selenium.hello;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HelloSelenium {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();

        driver.get("https://selenium.dev");

        driver.quit();
    }
}
from selenium import webdriver


driver = webdriver.Chrome()

driver.get("http://selenium.dev")

driver.quit()
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Hello;

public static class HelloSelenium
{
    public static void Main()
    {
        var driver = new ChromeDriver();
            
        driver.Navigate().GoToUrl("https://selenium.dev");
            
        driver.Quit();
    }
}
# frozen_string_literal: true

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :chrome

driver.get 'https://selenium.dev'

driver.quit
const {Builder, Browser} = require('selenium-webdriver');

(async function helloSelenium() {
  let driver = await new Builder().forBrowser(Browser.CHROME).build();

  await driver.get('https://selenium.dev');

  await driver.quit();
})();
package dev.selenium.hello

import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()

    driver.get("https://selenium.dev")

    driver.quit()
}

Consulte a Visão Geral para verificar os diferentes componentes do projeto e decidir se o Selenium é a ferramenta certa para você.

Você deve continuar no Guia de Introdução para entender como instalar o Selenium e usá-lo com sucesso como uma ferramenta de automação de teste e dimensionar testes simples como esse para serem executados em ambientes grandes e distribuídos em vários navegadores e em vários sistemas operacionais diferentes.

1 - Resumo

Será Selenium a ferramenta para você? Veja um resumo dos componentes do projecto.

Selenium não é só uma ferramenta ou API, mas sim uma composição de várias ferramentas.

WebDriver

Se você está começando com automação de testes de um site de desktop ou site para celular, então vai usar as APIs WebDriver. O WebDriver usa APIs de automação de navegador disponibilizadas por fornecedores de navegador para o controlar e executar testes. É como se um usuário real o estivesse operando. Como o WebDriver não exige que sua API seja compilada com o código do aplicativo, não é intrusivo. Portanto, você está testando o mesmo aplicativo que você envia aos ambientes de produção.

IDE

IDE (Ambiente de Desenvolvimento Integrado, em português) é a ferramenta que você usa para desenvolver seus casos de teste Selenium. É uma extensão para Chrome e Firefox fácil de usar e geralmente é a maneira mais eficiente de desenvolver casos de teste. Ela registra as ações dos usuários no navegador para você, usando comandos Selenium existentes, com parâmetros definidos pelo contexto daquele elemento. Isso não é apenas uma economia de tempo, mas também uma maneira excelente de aprender a sintaxe de script do Selenium.

Grid

Selenium Grid permite que você execute casos de teste em diferentes máquinas em diferentes plataformas. O controle para acionar os casos de teste está na extremidade local, e quando os casos de teste são acionados, eles são automaticamente executados pela extremidade remota.

Após o desenvolvimento dos testes WebDriver, você pode enfrentar a necessidade de executar seus testes em vários navegadores e combinações de sistemas operacionais. É aqui que o Grid entra em cena.

1.1 - Entendendo os componentes

Construir um conjunto de testes usando WebDriver exigirá que você entenda e use efetivamente uma série de componentes diferentes. Como com tudo em software, pessoas diferentes usam termos diferentes para a mesma ideia. Abaixo está uma análise de como os termos são usados nesta descrição.

Terminologia

  • API: interface de programação de aplicativo. Este é o conjunto de “comandos” que você usa para manipular o WebDriver.
  • Biblioteca: um módulo de código que contém as APIs e o código necessário para implementá-los. As bibliotecas são específicas para cada linguagem, por exemplo arquivos .jar para Java, arquivos .dll para .NET, etc.
  • Driver: responsável por controlar o navegador atual. A maioria dos drivers são criados pelos próprios fornecedores de navegadores. Os drivers são geralmente módulos executáveis ​​que são executados no sistema com o próprio navegador, não no sistema que está executando o conjunto de testes. (Embora esses possam ser mesmo sistema.) NOTA: Algumas pessoas se referem aos drivers como proxies.
  • Framework: uma biblioteca adicional usada como suporte para suítes do WebDriver.
  • Essas estruturas podem ser estruturas de teste, como JUnit ou NUnit. Eles também podem ser estruturas que suportam recursos de linguagem natural, como como Cucumber ou Robot Framework. Frameworks também podem ser escritos e usados ​​para coisas como manipulação ou configuração do sistema em teste, criação de dados, oráculos de teste, etc.

As partes e peças

No mínimo, o WebDriver se comunica com um navegador por meio de um driver. Comunicação é bidirecional: o WebDriver passa comandos para o navegador por meio do driver e recebe informações de volta pela mesma rota.

Basic Communication

O driver é específico para o navegador, como ChromeDriver para Google Chrome / Chromium, GeckoDriver para Mozilla Firefox, etc. O driver é executado no mesmo sistema do navegador. Este pode, ou não ser, o mesmo sistema onde os próprios testes estão sendo executados.

Este exemplo simples acima é comunicação direta. Comunicação para o navegador também pode ser comunicação remota através do servidor Selenium ou RemoteWebDriver. RemoteWebDriver roda no mesmo sistema que o driver e o navegador.

Remote Communication

A comunicação remota também pode ocorrer usando Selenium Server ou Selenium Grid, que, por sua vez, fala com o driver no sistema host

Remote Communication with Grid

Onde frameworks se encaixam

O WebDriver tem um trabalho e apenas um trabalho: comunicar-se com o navegador por meio de qualquer um dos métodos acima. O WebDriver não sabe nada sobre testes: ele não sabe como comparar coisas, afirmar passa ou falha, e certamente não sabe uma coisa sobre relatórios ou gramática Dado / Quando / Então.

É aqui que vários frameworks entram em cena. No mínimo, você precisará de um framework de teste que corresponde às linguagens, por exemplo, NUnit para .NET, JUnit para Java, RSpec para Ruby, etc.

O framework de teste é responsável por rodar e executar seu WebDriver e etapas relacionadas em seus testes. Como tal, você pode pensar nele parecendo a imagem seguinte.

Estrutura de Teste

Frameworks/ferramentas de linguagem natural, como Cucumber, podem existir como parte desse framework de teste na figura acima, ou eles podem envolver o framework de teste inteiramente em sua própria implementação.

1.2 - Detalhes

Selenium é um projeto abrangente para uma gama de ferramentas e bibliotecas que permitem e suportam a automação de navegadores da web.

Selenium controla navegadores

Selenium é muitas coisas mas, em sua essência, é um conjunto de ferramentas para automação de navegador da web que usa as melhores técnicas disponíveis para controlar remotamente as instâncias do navegador e emular a interação do usuário com o navegador.

Ele permite que os usuários simulem atividades comuns realizadas por usuários finais; inserir texto em campos, selecionando valores suspensos e caixas de seleção, e clicar em links em documentos. Ele também fornece muitos outros controles, como o movimento do mouse, execução arbitrária de JavaScript e muito mais.

Embora seja usado principalmente para testes de front-end de sites, Selenium é basicamente uma biblioteca de agente de usuário de navegador. As interfaces são onipresentes em seus aplicativos, o que incentiva a composição com outras bibliotecas para atender a sua finalidade.

Uma interface para tudo

Um dos princípios norteadores do projeto é oferecer suporte a uma interface comum para todas as tecnologias de navegador (principais). Os navegadores da web são aplicativos incrivelmente complexos e altamente projetados, realizando suas operações de maneiras completamente diferentes mas que frequentemente têm a mesma aparência ao fazê-lo. Mesmo que o texto seja renderizado com as mesmas fontes, as imagens sejam exibidas no mesmo lugar e os links levem você ao mesmo destino. O que está acontecendo por baixo é tão diferente quanto noite e dia. Selenium “abstrai” essas diferenças, esconde seus detalhes e complexidades da pessoa que está escrevendo o código. Isso permite que você escreva várias linhas de código para realizar um fluxo de trabalho complicado, mas essas mesmas linhas serão executadas no Firefox, Internet Explorer, Chrome e todos os outros navegadores compatíveis.

Ferramentas e suporte

A abordagem de design minimalista do Selenium lhe dá a versatilidade para ser incluído como um componente em aplicações maiores. A infraestrutura circundante fornecida sob o Selenium dá a você as ferramentas para montar sua Grid de navegadores para que os testes possam ser executados em diferentes navegadores e sistemas operacionais em uma variedade de máquinas.

Imagine um banco de computadores em sua sala de servidores ou data center todos abrindo navegadores ao mesmo tempo acessando links, formulários, e tabelas — testando seu aplicativo 24 horas por dia. Por meio da interface de programação simples fornecido para os idiomas mais comuns, esses testes serão executados incansavelmente em paralelo, reportando de volta para você quando ocorrerem erros.

É o objetivo de ajudar a tornar isso uma realidade para você, fornecendo aos usuários ferramentas e documentação não apenas para controlar os navegadores mas para tornar mais fácil dimensionar e implantar essas grades.

Quem usa Selenium

Muitas das empresas mais importantes do mundo adotaram o Selenium para seus testes baseados em navegador, frequentemente substituindo esforços de anos envolvendo outras ferramentas proprietárias. À medida que sua popularidade cresceu, seus requisitos e desafios se multiplicaram.

Conforme a web se torna mais complicada e novas tecnologias são adicionadas aos sites, é a missão deste projeto acompanhá-los sempre que possível. Sendo um projeto de código aberto, este apoio é fornecido por meio da generosa doação de tempo de muitos voluntários, cada um deles tem um “trabalho diurno”.

Outra missão do projeto é incentivar mais voluntários para participar deste esforço, e construir uma comunidade forte para que o projeto possa continuar a acompanhar as tecnologias emergentes e permanecer uma plataforma dominante para automação de teste funcional.

2 - WebDriver

WebDriver manipula um navegador nativamente; aprenda mais sobre isso.

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.

Selenium WebDriver é uma recomendação W3C

  • 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.

2.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.

2.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.

Requisitos por linguagem

Veja a mínima versão do Java suportada aqui.

A instalação da biblioteca Selenium para Java é feita a partir de uma build tool.

Maven

Especifique a dependência no pom.xml do seu projeto.

            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>

Gradle

Especifique a dependência no build.gradle do seu projeto como testImplementation:


dependencies {

A mínima versão suportada do Python para cada versão do Selenium pode ser encontrada em “Supported Python Versions” no PyPi.

Existe muitas formas diferentes de instalar Selenium.

Pip

pip install selenium

Download

Como uma alternativa você pode baixar o código fonte PyPI (selenium-x.x.x.-py3-none-any.whl) e instalar usando pip:

pip install selenium-x.x.x.-py3-none-any.whl

Exigir em um projeto

Para usar em um projeto, adicione no arquivo requirements.txt.

selenium==4.41.0

Uma lista com todos os frameworks suportados para cada versão do Selenium pode ser encontrada em Nuget

Existe algumas opções para instalar o Selenium.

Packet Manager

Install-Package Selenium.WebDriver

.NET CLI

dotnet add package Selenium.WebDriver

CSProj

No arquivo csproj do seu projeto, especifique a dependência como PackageReference no ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.41.0" />

Considerações adicionais

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:

<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />   
  </packageSources>
...

Para mais informações sobre nuget.config clique 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.

Instalação manual

gem install selenium-webdriver

Adicione para o gemfile do projeto

gem 'selenium-devtools', '= 0.147.0'

Você pode encontrar a mínima versão suportada do Node para cada versão do Selenium na seção Node Support Policy no site npmjs

Selenium é normalmente instalado usando npm.

Instalação local

npm install selenium-webdriver

Adicione ao seu projeto

No package.json do seu projeto, adicione os requisitos em dependencies:

        "mocha": "11.7.5"
Use as ligações Java para Kotlin.

Próximo passo

Programando o seu primeiro script Selenium

2.1.2 - Programe o seu primeiro script Selenium

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

        WebDriver driver = new ChromeDriver();
driver = webdriver.Chrome()
        IWebDriver driver = new ChromeDriver();
driver = Selenium::WebDriver.for :chrome
    driver = await new Builder().forBrowser(Browser.CHROME).build();
        driver = ChromeDriver()

2. Agindo no navegador de internet

Nesse exemplo estamos navegando para uma página web.

        driver.get("https://www.selenium.dev/selenium/web/web-form.html");
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
        driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/web-form.html");
driver.get('https://www.selenium.dev/selenium/web/web-form.html')
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
        driver.get("https://www.selenium.dev/selenium/web/web-form.html")

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.

        driver.getTitle();
title = driver.title
        var title = driver.Title;
driver.title
    let title = await driver.getTitle();
        val title = driver.title

4. Estabelecendo uma Estratégia de Espera

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.

Leia mais sobre Estratégias de espera.

        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.implicitly_wait(0.5)
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
driver.manage.timeouts.implicit_wait = 500
    await driver.manage().setTimeouts({implicit: 500});
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))

5. Encontrando um elemento

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

        WebElement textBox = driver.findElement(By.name("my-text"));
        WebElement submitButton = driver.findElement(By.cssSelector("button"));
text_box = driver.find_element(by=By.NAME, value="my-text")
submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button")
        var textBox = driver.FindElement(By.Name("my-text"));
        var submitButton = driver.FindElement(By.TagName("button"));
text_box = driver.find_element(name: 'my-text')
submit_button = driver.find_element(tag_name: 'button')
    let textBox = await driver.findElement(By.name('my-text'));
    let submitButton = await driver.findElement(By.css('button'));
        var textBox = driver.findElement(By.name("my-text"))
        val submitButton = driver.findElement(By.cssSelector("button"))

6. Agindo no elemento

Há apenas um punhado de ações a serem executadas em um elemento, mas você irá usá-las com frequência.

        textBox.sendKeys("Selenium");
        submitButton.click();
text_box.send_keys("Selenium")
submit_button.click()
        textBox.SendKeys("Selenium");
        submitButton.Click();
text_box.send_keys('Selenium')
submit_button.click
    await textBox.sendKeys('Selenium');
    await submitButton.click();
        textBox.sendKeys("Selenium")
        submitButton.click()

7. Solicitando informações do elemento

Elementos podem guardar muitas informações que podem ser solicitadas.

        WebElement message = driver.findElement(By.id("message"));
        message.getText();
message = driver.find_element(by=By.ID, value="message")
text = message.text
        var message = driver.FindElement(By.Id("message"));
        var value = message.Text;
message = driver.find_element(id: 'message')
message.text
    let message = await driver.findElement(By.id('message'));
    let value = await message.getText();
        val message = driver.findElement(By.id("message"))
        val value = message.getText()

8. Encerrando a sessão

Isso encerra o processo do driver, que por padrão também fecha o navegador. Nenhum outro comando pode ser enviado para esta instância do driver.

See Quitting Sessions.

        driver.quit();
driver.quit()
        driver.Quit();
driver.quit
    await driver.quit();
        driver.quit()

Running Selenium File

mvn exec:java -D"exec.mainClass"="dev.selenium.getting_started.FirstScript" -D"exec.classpathScope"=test
```
dotnet test --filter "FullyQualifiedName=SeleniumDocs.GettingStarted.UsingSeleniumTest.EightComponents"
ruby example_script.rb
node example_script.spec.js

Próximos Passos

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.

2.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…

Executador de teste

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:

Afirmar

		String title = driver.getTitle();
		assertEquals("Web form", title);
    title = driver.title
    assert title == "Web form"
            var title = driver.Title;
            Assert.AreEqual("Web form", title);
    title = @driver.title
    expect(title).to eq('Web form')
    let title = await driver.getTitle();
    assert.equal("Web form", title);
        val title = driver.title
        assertEquals("Web form", title)

Configuarar e Desconfigurar

Set Up

	@BeforeEach
	public void setup() {
		driver = new ChromeDriver();
	}

Tear Down

	@AfterEach
	public final void teardown() {
		if (driver != null) {
			driver.quit();

Set Up

def setup():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")
    return driver

Tear Down

def teardown(driver):
    driver.quit()

Set Up

  before do
    @driver = Selenium::WebDriver.for :chrome
  end

Tear Down

  config.after { @driver&.quit }
### Set Up
  before(async function () {
    driver = await new Builder().forBrowser('chrome').build();
  });
### Tear Down
  after(async () => await driver.quit());

Executando

Maven

mvn clean test

Gradle

gradle clean test
```
dotnet test
bundle exec rspec

Mocha

mocha runningTests.spec.js

npx

npx mocha runningTests.spec.js

Examplos

In First script, we saw each of the components of a Selenium script. Here’s an example of that code using a test runner:

package dev.selenium.getting_started;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Duration;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class UsingSeleniumTest {

	WebDriver driver;

	@BeforeEach
	public void setup() {
		driver = new ChromeDriver();
	}

	@Test
	public void eightComponents() {

		driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
		driver.get("https://www.selenium.dev/selenium/web/web-form.html");

		String title = driver.getTitle();
		assertEquals("Web form", title);

		WebElement textBox = driver.findElement(By.name("my-text"));
		WebElement submitButton = driver.findElement(By.cssSelector("button"));

		textBox.sendKeys("Selenium");
		submitButton.click();

		WebElement message = driver.findElement(By.id("message"));
		String value = message.getText();
		assertEquals("Received!", value);

	}

	@AfterEach
	public final void teardown() {
		if (driver != null) {
			driver.quit();
		}
	}

}
from selenium import webdriver
from selenium.webdriver.common.by import By


def test_eight_components():
    driver = setup()

    title = driver.title
    assert title == "Web form"

    driver.implicitly_wait(0.5)

    text_box = driver.find_element(by=By.NAME, value="my-text")
    submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button")

    text_box.send_keys("Selenium")
    submit_button.click()

    message = driver.find_element(by=By.ID, value="message")
    value = message.text
    assert value == "Received!"

    teardown(driver)

def setup():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")
    return driver

def teardown(driver):
    driver.quit()
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.GettingStarted
{
    [TestClass]
    public class UsingSeleniumTest
    {

        [TestMethod]
        public void EightComponents()
        {
            IWebDriver driver = new ChromeDriver();

            driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/web-form.html");

            var title = driver.Title;
            Assert.AreEqual("Web form", title);

            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            var textBox = driver.FindElement(By.Name("my-text"));
            var submitButton = driver.FindElement(By.TagName("button"));
            
            textBox.SendKeys("Selenium");
            submitButton.Click();
            
            var message = driver.FindElement(By.Id("message"));
            var value = message.Text;
            Assert.AreEqual("Received!", value);
            
            driver.Quit();
        }
    }
}
# frozen_string_literal: true

require 'spec_helper'
require 'selenium-webdriver'

RSpec.describe 'Using Selenium' do
  before do
    @driver = Selenium::WebDriver.for :chrome
  end

  it 'uses eight components' do
    @driver.get('https://www.selenium.dev/selenium/web/web-form.html')

    title = @driver.title
    expect(title).to eq('Web form')

    @driver.manage.timeouts.implicit_wait = 500

    text_box = @driver.find_element(name: 'my-text')
    submit_button = @driver.find_element(tag_name: 'button')

    text_box.send_keys('Selenium')
    submit_button.click

    message = @driver.find_element(id: 'message')
    value = message.text
    expect(value).to eq('Received!')
  end
end
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");

describe('First script', function () {
  let driver;

  before(async function () {
    driver = await new Builder().forBrowser('chrome').build();
  });

  it('First Selenium script with mocha', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/web-form.html');

    let title = await driver.getTitle();
    assert.equal("Web form", title);

    await driver.manage().setTimeouts({implicit: 500});

    let textBox = await driver.findElement(By.name('my-text'));
    let submitButton = await driver.findElement(By.css('button'));

    await textBox.sendKeys('Selenium');
    await submitButton.click();

    let message = await driver.findElement(By.id('message'));
    let value = await message.getText();
    assert.equal("Received!", value);
  });

  after(async () => await driver.quit());
});

Proximos passos

Pegue no que aprendeu e desenvolva o seu código Selenium!

À medida que encontrar mais funcionalidades de que precisa, leia o resto da nossa documentação do WebDriver.

2.2 - Sessões de Driver

Iniciar e encerrar uma sessão serve para abrir e fechar um navegador.

Criando Sessões

Criar uma nova sessão corresponde ao comando W3C para Nova sessão

A sessão é criada automaticamente ao inicializar um novo objeto da classe Driver.

Cada linguagem permite que uma sessão seja criada com argumentos de uma dessas classes (ou equivalentes):

Local Driver

O principal argumento exclusivo para iniciar um driver local inclui informações sobre a inicialização do serviço de driver necessário na máquina local.

  • Objeto de Serviço se aplica apenas a drivers locais e fornece informações sobre o driver do navegador.
    WebDriver driver = new ChromeDriver(chromeOptions);
    driver = webdriver.Chrome(options=options)
            driver = new ChromeDriver(options);
      driver = Selenium::WebDriver.for :chrome, options: options
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options)
      .setChromeService(service)
      .build();

Driver Remoto

O principal argumento exclusivo para iniciar um driver remoto inclui informações sobre onde executar o código. Leia os detalhes na seção Driver Remoto

Encerrando Sessões

Encerrar uma sessão corresponde ao comando W3C para Excluir uma Sessão.

Nota importante: o método quit é diferente do método close, e é recomendável sempre usar quit para finalizar a sessão.

        driver.quit();
    driver.quit()
        driver.Quit();
      driver.quit
    await driver.quit();
        driver.quit()

2.2.1 - Opções do navegador

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á.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	String name = chromeOptions.getBrowserName();
    options = get_default_chrome_options()
    assert options.capabilities['browserName'] == 'chrome'
      options = Selenium::WebDriver::Options.chrome

browserVersion

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á.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	String version = "latest";
	chromeOptions.setBrowserVersion(version);
    options = get_default_chrome_options()
    options.browser_version = 'stable'
    assert options.capabilities['browserVersion'] == 'stable'
      options.browser_version = 'latest'

pageLoadStrategy

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égiaEstado prontoNotas
normalcompletoUsado por padrão, aguarda o download de todos os recursos
ansiosointerativoO acesso DOM está pronto, mas outros recursos como imagens ainda podem estar carregando
nenhumQualquerNã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.

    ChromeOptions chromeOptions = getDefaultChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = get_default_chrome_options()
    options.page_load_strategy = 'normal'
    driver = webdriver.Chrome(options=options)
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :normal
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('normal'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

eager

WebDriver waits until DOMContentLoaded event fire is returned.

    ChromeOptions chromeOptions = getDefaultChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = get_default_chrome_options()
    options.page_load_strategy = 'eager'
    driver = webdriver.Chrome(options=options)
            var chromeOptions = new ChromeOptions();
            chromeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :eager
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('eager'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

none

WebDriver only waits until the initial page is downloaded.

    ChromeOptions chromeOptions = getDefaultChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = get_default_chrome_options()
    options.page_load_strategy = 'none'
    driver = webdriver.Chrome(options=options)
        [TestMethod]
        public void SetPageLoadStrategyNone()
      options = Selenium::WebDriver::Options.chrome
      options.page_load_strategy = :none
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setPageLoadStrategy('none'))
      .build();

    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
    await driver.quit();
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

fun main() {
  val chromeOptions = ChromeOptions()
  chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE)
  val driver = ChromeDriver(chromeOptions)
  try {
    driver.get("https://www.google.com")
  }
  finally {
    driver.quit()
  }
}

platformName

This identifies the operating system at the remote-end, fetching the platformName returns the OS name.

In cloud-based providers, setting platformName sets the OS at the remote-end.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	String platform = "OS X 10.6";
	chromeOptions.setPlatformName(platform);
    options = get_default_chrome_options()
    options.platform_name = 'any'
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.firefox
      options.platform_name = 'Windows 10'

acceptInsecureCerts

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.

    ChromeOptions chromeOptions = getDefaultChromeOptions();
    chromeOptions.setAcceptInsecureCerts(true);
    options = get_default_chrome_options()
    options.accept_insecure_certs = True
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.accept_insecure_certs = true
    let driver = new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options.setAcceptInsecureCerts(true))
      .build();

timeouts

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.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setScriptTimeout(duration);
    options = get_default_chrome_options()
    options.timeouts = { 'script': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {script: 40_000}

Page Load Timeout

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.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setPageLoadTimeout(duration);
    options = get_default_chrome_options()
    options.timeouts = { 'pageLoad': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {page_load: 400_000}

Implicit Wait Timeout

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.

	ChromeOptions chromeOptions = getDefaultChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setImplicitWaitTimeout(duration);
    options = get_default_chrome_options()
    options.timeouts = { 'implicit': 5000 }
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.timeouts = {implicit: 1}

unhandledPromptBehavior

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:

  • dismiss
  • accept
  • dismiss and notify
  • accept and notify
  • ignore
	ChromeOptions chromeOptions = getDefaultChromeOptions();
	chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);
    options = get_default_chrome_options()
    options.unhandled_prompt_behavior = 'accept'
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.unhandled_prompt_behavior = :accept

setWindowRect

Indicates whether the remote end supports all of the resizing and repositioning commands.

   	ChromeOptions chromeOptions = getDefaultChromeOptions();
   	chromeOptions.setCapability(CapabilityType.SET_WINDOW_RECT, true);
    options = webdriver.FirefoxOptions()
    options.set_window_rect = True # Full support in Firefox
    driver = webdriver.Firefox(options=options)
      options = Selenium::WebDriver::Options.firefox
      options.set_window_rect = true

strictFileInteractability

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.

    ChromeOptions chromeOptions = getDefaultChromeOptions();
    chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY, true);
    options = get_default_chrome_options()
    options.strict_file_interactability = True
    driver = webdriver.Chrome(options=options)
      options = Selenium::WebDriver::Options.chrome
      options.strict_file_interactability = true

proxy

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:

Move Code

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ProxyTest {
  public static void main(String[] args) {
    Proxy proxy = new Proxy();
    proxy.setHttpProxy("<HOST:PORT>");
    ChromeOptions options = new ChromeOptions();
    options.setCapability("proxy", proxy);
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com/");
    driver.manage().window().maximize();
    driver.quit();
  }
}
    options = get_default_chrome_options()
    options.proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy' : 'http.proxy:1234'})
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

public class ProxyTest{
public static void Main() {
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = "<HOST:PORT>";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.selenium.dev/");
}
}
      options = Selenium::WebDriver::Options.chrome
      options.proxy = Selenium::WebDriver::Proxy.new(http: 'myproxy.com:8080')
let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let proxy = require('selenium-webdriver/proxy');
let opts = new chrome.Options();

(async function example() {
opts.setProxy(proxy.manual({http: '<HOST:PORT>'}));
let driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get("https://selenium.dev");
}
finally {
await driver.quit();
}
}());
import org.openqa.selenium.Proxy
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

class proxyTest {
fun main() {

        val proxy = Proxy()
        proxy.setHttpProxy("<HOST:PORT>")
        val options = ChromeOptions()
        options.setCapability("proxy", proxy)
        val driver: WebDriver = ChromeDriver(options)
        driver["https://www.google.com/"]
        driver.manage().window().maximize()
        driver.quit()
    }
}

2.2.2 - Configuração do Cliente HTTP

These allow you to set various parameters for the HTTP library

package dev.selenium.drivers;

import dev.selenium.BaseTest;

import org.openqa.selenium.remote.http.ClientConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.net.URL;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;

import org.openqa.selenium.UsernameAndPassword;

import static java.net.http.HttpClient.Version.HTTP_1_1;

public class HttpClientTest extends BaseTest {
    URL gridUrl;

    @BeforeEach
    public void startGrid() {
        gridUrl = startStandaloneGridAdvanced();
    }

    @Test
    public void remoteWebDriverWithClientConfig() throws Exception {
        ClientConfig clientConfig = ClientConfig.defaultConfig()
                .withRetries()
                .sslContext(createSSLContextWithCA(Path.of("src/test/resources/tls.crt").toAbsolutePath().toString()))
                .connectionTimeout(Duration.ofSeconds(300))
                .readTimeout(Duration.ofSeconds(3600))
                .authenticateAs(new UsernameAndPassword("admin", "myStrongPassword"))
                .version(HTTP_1_1.toString());
        ChromeOptions options = getDefaultChromeOptions();
        options.setEnableDownloads(true);
        driver = RemoteWebDriver.builder()
                .oneOf(options)
                .address(gridUrl)
                .config(clientConfig)
                .build();
    }

    @Test
    public void remoteWebDriverIgnoreSSL() throws Exception {
        ClientConfig clientConfig = ClientConfig.defaultConfig()
                .withRetries()
                .sslContext(createIgnoreSSLContext())
                .connectionTimeout(Duration.ofSeconds(300))
                .readTimeout(Duration.ofSeconds(3600))
                .authenticateAs(new UsernameAndPassword("admin", "myStrongPassword"))
                .version(HTTP_1_1.toString());
        ChromeOptions options = getDefaultChromeOptions();
        options.setEnableDownloads(true);
        driver = RemoteWebDriver.builder()
                .oneOf(options)
                .address(gridUrl)
                .config(clientConfig)
                .build();
    }

    @Test
    public void remoteWebDriverWithEmbedAuthUrl() throws Exception {
        ClientConfig clientConfig = ClientConfig.defaultConfig()
                .withRetries()
                .sslContext(createSSLContextWithCA(Path.of("src/test/resources/tls.crt").toAbsolutePath().toString()))
                .connectionTimeout(Duration.ofSeconds(300))
                .readTimeout(Duration.ofSeconds(3600))
                .version(HTTP_1_1.toString());
        ChromeOptions options = getDefaultChromeOptions();
        options.setEnableDownloads(true);
        driver = RemoteWebDriver.builder()
                .oneOf(options)
                .address(embedAuthToUrl(gridUrl, "admin", "myStrongPassword"))
                .config(clientConfig)
                .build();
    }

    private URL embedAuthToUrl(URL url, String username, String password) throws Exception {
        String userInfo = username + ":" + password;
        String urlWithAuth = url.getProtocol() + "://" + userInfo + "@" + url.getHost() + ":" + url.getPort() + url.getPath();
        return new URL(urlWithAuth);
    }

    public static SSLContext createSSLContextWithCA(String caCertPath) throws Exception {
        FileInputStream fis = new FileInputStream(caCertPath);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate caCert = (X509Certificate) cf.generateCertificate(fis);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("caCert", caCert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext;
    }

    public static SSLContext createIgnoreSSLContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        return sslContext;
    }
}
import os
import pytest
import sys
from urllib3.util import Retry, Timeout
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.client_config import ClientConfig


@pytest.mark.skipif(sys.platform == "win32", reason="Gets stuck on Windows, passes locally")
def test_start_remote_with_client_config(grid_server):
    proxy = Proxy({"proxyType": ProxyType.AUTODETECT})
    retries = Retry(connect=2, read=2, redirect=2)
    timeout = Timeout(connect=300, read=3600)
    client_config = ClientConfig(remote_server_addr=grid_server,
                                 proxy=proxy,
                                 init_args_for_pool_manager={
                                     "init_args_for_pool_manager": {"retries": retries, "timeout": timeout}},
                                 ca_certs=_get_resource_path("tls.crt"),
                                 username="admin", password="myStrongPassword")
    options = get_default_chrome_options()
    driver = webdriver.Remote(command_executor=grid_server, options=options, client_config=client_config)
    driver.get("https://www.selenium.dev")
    driver.quit()


@pytest.mark.skipif(sys.platform == "win32", reason="Gets stuck on Windows, passes locally")
def test_start_remote_ignore_certs(grid_server):
    proxy = Proxy({"proxyType": ProxyType.AUTODETECT})
    client_config = ClientConfig(remote_server_addr=grid_server,
                                 proxy=proxy,
                                 timeout=3600,
                                 ignore_certificates=True,
                                 username="admin", password="myStrongPassword")
    options = get_default_chrome_options()
    driver = webdriver.Remote(command_executor=grid_server, options=options, client_config=client_config)
    driver.get("https://www.selenium.dev")
    driver.quit()


def _get_resource_path(file_name: str):
    if os.path.abspath("").endswith("tests"):
        path = os.path.abspath(f"resources/{file_name}")
    else:
        path = os.path.abspath(f"tests/resources/{file_name}")
    return path

def get_default_chrome_options():
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    return options

  it 'sets client configuration' do

2.2.3 - Classe de Serviço do Driver

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:

    ChromeDriverService service = new ChromeDriverService.Builder().build();
    driver = new ChromeDriver(service);

Selenium v4.11

    service = webdriver.ChromeService()
    driver = webdriver.Chrome(service=service)
            var service = ChromeDriverService.CreateDefaultService();
            driver = new ChromeDriver(service);
    service = Selenium::WebDriver::Service.chrome
    @driver = Selenium::WebDriver.for :chrome, service: service

Driver location

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:

    ChromeDriverService service =
        new ChromeDriverService.Builder().usingDriverExecutable(driverPath).build();

Selenium v4.11

    service = webdriver.ChromeService(executable_path=chromedriver_bin)

Selenium v4.9

            var service = ChromeDriverService.CreateDefaultService(GetDriverLocation(options));

Selenium v4.8

    service.executable_path = driver_path

Driver port

If you want the driver to run on a specific port, you may specify it as follows:

    ChromeDriverService service = new ChromeDriverService.Builder().usingPort(1234).build();

Selenium v4.11

    service = webdriver.ChromeService(port=1234)
            service.Port = 1234;

Selenium v4.8

    service.port = 1234

Logging

Logging functionality varies between browsers. Most browsers allow you to specify location and level of logs. Take a look at the respective browser page:

2.2.4 - WebDriver Remoto

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.

    ChromeOptions options = getDefaultChromeOptions();
    driver = new RemoteWebDriver(gridUrl, options);
    options = get_default_chrome_options()
    driver = webdriver.Remote(command_executor=server, options=options)
            var options = new ChromeOptions();
            driver = new RemoteWebDriver(GridUrl, options);
    options = Selenium::WebDriver::Options.chrome
    driver = Selenium::WebDriver.for :remote, url: grid_url, options: options

Uploads

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.
    ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
    WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
    fileInput.sendKeys(uploadFile.getAbsolutePath());
    driver.findElement(By.id("file-submit")).click();

Python adds a local file detector to remote webdriver instances by default, but you can also create your own class.

    driver.file_detector = LocalFileDetector()
    file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
    file_input.send_keys(upload_file)
    driver.find_element(By.ID, "file-submit").click()
.NET adds a local file detector to remote webdriver instances by default, but you can also create your own class.
            ((RemoteWebDriver)driver).FileDetector = new LocalFileDetector();
            IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
            fileInput.SendKeys(uploadFile);
            driver.FindElement(By.Id("file-submit")).Click();
Ruby adds a local file detector to remote webdriver instances by default, but you can also create your own lambda:
    driver.file_detector = ->((filename, *)) { filename.include?('selenium') && filename }
    file_input = driver.find_element(css: 'input[type=file]')
    file_input.send_keys(upload_file)
    driver.find_element(id: 'file-submit').click

Downloads

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.

    ChromeOptions options = getDefaultChromeOptions();
    options.setEnableDownloads(true);
    driver = new RemoteWebDriver(gridUrl, options);
    options = get_default_chrome_options()
    options.enable_downloads = True
    driver = webdriver.Remote(command_executor=server, options=options)
            ChromeOptions options = new ChromeOptions
            {
                EnableDownloads = true
            };

            driver = new RemoteWebDriver(GridUrl, options);
    options = Selenium::WebDriver::Options.chrome(enable_downloads: true)
    driver = Selenium::WebDriver.for :remote, url: grid_url, options: options

List Downloadable Files

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.

    List<String> files = ((HasDownloads) driver).getDownloadableFiles();
    files = driver.get_downloadable_files()
            IReadOnlyList<string> names = ((RemoteWebDriver)driver).GetDownloadableFiles();
    files = driver.downloadable_files

Download a File

Selenium looks for the name of the provided file in the list and downloads it to the provided target directory.

    ((HasDownloads) driver).downloadFile(downloadableFile, targetDirectory);
    driver.download_file(downloadable_file, target_directory)
            ((RemoteWebDriver)driver).DownloadFile(downloadableFile, targetDirectory);
    driver.download_file(downloadable_file, target_directory)

Delete Downloaded Files

By default, the download directory is deleted at the end of the applicable session, but you can also delete all files during the session.

    ((HasDownloads) driver).deleteDownloadableFiles();
    driver.delete_downloadable_files()
            ((RemoteWebDriver)driver).DeleteDownloadableFiles();
    driver.delete_downloadable_files

Browser specific functionalities

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

    driver = new Augmenter().augment(driver);

Of interest, using the RemoteWebDriverBuilder automatically augments the driver, so it is a great way to get all the functionality by default:

        RemoteWebDriver.builder()
            .address(gridUrl)
            .oneOf(getDefaultChromeOptions())
            .setCapability("ext:options", Map.of("key", "value"))
            .config(ClientConfig.defaultConfig())
            .build();
.NET uses a custom command executor for executing commands that are valid for the given browser in the remote driver.
            var customCommandDriver = driver as ICustomDriverCommandExecutor;
            customCommandDriver.RegisterCustomDriverCommands(FirefoxDriver.CustomCommandDefinitions);

            var screenshotResponse = customCommandDriver
                .ExecuteCustomDriverCommand(FirefoxDriver.GetFullPageScreenshotCommand, null);
Ruby uses mixins to add applicable browser specific methods to the Remote WebDriver session; the methods should always just work for you.

Tracing client requests

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:

  <dependency>
      <groupId>io.opentelemetry</groupId>
      <artifactId>opentelemetry-exporter-jaeger</artifactId>
      <version>1.0.0</version>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty</artifactId>
      <version>1.35.0</version>
    </dependency>

Add/pass the required system properties while running the client

System.setProperty("otel.traces.exporter", "jaeger");
System.setProperty("otel.exporter.jaeger.endpoint", "http://localhost:14250");
System.setProperty("otel.resource.attributes", "service.name=selenium-java-client");

ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");

WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), capabilities);

driver.get("http://www.google.com");

driver.quit();

Please refer to Tracing Setup for more information on external dependencies versions required for the desired Selenium version.

More information can be found at:

2.3 - Navegadores suportados

Cada navegador tem capacidades e características únicas.

2.3.1 - Funcionalidade específica do Chrome

Estas capacidades e características são específicas ao navegador Google Chrome.

Por omissão, Selenium 4 é compatível com Chrome v75 e superiores. Note que a versão (maior) do navegador e do chromedriver devem ser idênticas.

Opções

Capacidades comuns a todos os navegadores estão descritas na página Opções.

Capacidades únicas ao Chrome podem ser encontradas na página da Google para Capacidades e & ChromeOptions

Este é um exemplo de como iniciar uma sessão Chrome com um conjunto de opções básicas:

    System.clearProperty(ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY);
  }