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 = new ChromeOptions();
	String name = chromeOptions.getBrowserName();
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
	String version = "latest";
	chromeOptions.setBrowserVersion(version);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'normal'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      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 = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'eager'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      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 = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
    WebDriver driver = new ChromeDriver(chromeOptions);
    options = webdriver.ChromeOptions()
    options.page_load_strategy = 'none'
    driver = webdriver.Chrome(options=options)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace pageLoadStrategy {
  class pageLoadStrategy {
    public static void Main(string[] args) {
      var chromeOptions = new ChromeOptions();
      chromeOptions.PageLoadStrategy = PageLoadStrategy.None;
      IWebDriver driver = new ChromeDriver(chromeOptions);
      try {
        driver.Navigate().GoToUrl("https://example.com");
      } finally {
        driver.Quit();
      }
    }
  }
}
      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 = new ChromeOptions();
	String platform = "OS X 10.6";
	chromeOptions.setPlatformName(platform);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
    chromeOptions.setAcceptInsecureCerts(true);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setScriptTimeout(duration);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setPageLoadTimeout(duration);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
	Duration duration = Duration.of(5, ChronoUnit.SECONDS);
	chromeOptions.setImplicitWaitTimeout(duration);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
	chromeOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY);
    options = webdriver.ChromeOptions()
    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 = new ChromeOptions();
   	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 = new ChromeOptions();
    chromeOptions.setCapability(CapabilityType.STRICT_FILE_INTERACTABILITY, true);
    options = webdriver.ChromeOptions()
    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 = webdriver.ChromeOptions()
    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()
    }
}