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