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:


def test_keep_browser_open():

      driver = new ChromeDriver(options);
  it 'basic options' do
    options = Selenium::WebDriver::Options.chrome
      const Options = new Chrome.Options();
      let driver = await env
        .builder()
        .setChromeOptions(Options)
        .build();

Alguns exemplos de uso com capacidades diferentes:

Argumentos

The args parameter is for a list of command line switches to be used when starting the browser. There are two excellent resources for investigating these arguments:

Commonly used args include --start-maximized, --headless=new and --user-data-dir=...

Add an argument to options:

    options = Selenium::WebDriver::Options.chrome(args: ['--headless=new'])
      let driver = await env
        .builder()
        .setChromeOptions(options.addArguments('--headless=new'))
        .build();

Iniciar navegador numa localização específica

Adicionar uma localização:

      let driver = await env
        .builder()
        .setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
        .build();

Adicionar extensões

O parametro extensions aceita ficheiros crx

The extensions parameter accepts crx files. As for unpacked directories, please use the load-extension argument instead, as mentioned in this post.

Adicionar uma extensão:

Manter o navegador aberto

Ao definir o parametro detach para true, irá manter o navegador aberto mesmo depois do driver fechar.

Adicionar detach:

Note: This is already the default behavior in Java.

Note: This is already the default behavior in .NET.

      let driver = await env
        .builder()
        .setChromeOptions(options.detachDriver(true))
        .build();

Excluindo parametros

Chrome adiciona vários parametros, se não os pretende adicionar, passe-os em excludeSwitches.

Um exemplo comum é voltar a activar o bloqueador de popups. A full list of default arguments can be parsed from the Chromium Source Code

Exclua parametros:

            options.AddExcludedArgument("disable-popup-blocking");
    @driver = Selenium::WebDriver.for :chrome, options: options
      let driver = await env
        .builder()
        .setChromeOptions(options.excludeSwitches('enable-automation'))
        .build();

Service

Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.

Log output

Getting driver logs can be helpful for debugging issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.

File output

To change the logging output to save to a specific file:

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));

Note: Java also allows setting file output by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: String representing path to log file

            service.LogPath = GetLogLocation();

Console output

To change the logging output to display in the console as STDOUT:

Selenium v4.10

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));

Note: Java also allows setting console output by System Property;
Property key: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT or DriverService.LOG_STDERR

$stdout and $stderr are both valid values

Selenium v4.10

      service.log = $stdout

Log level

There are 6 available log levels: ALL, DEBUG, INFO, WARNING, SEVERE, and OFF. Note that --verbose is equivalent to --log-level=ALL and --silent is equivalent to --log-level=OFF, so this example is just setting the log level generically:

Selenium v4.8

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));

Note: Java also allows setting log level by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of ChromiumDriverLogLevel enum

Selenium v4.10

      service.args << '--log-level=DEBUG'

Log file features

There are 2 features that are only available when logging to a file:

  • append log
  • readable timestamps

To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.

Selenium v4.8


        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));

Note: Java also allows toggling these features by System Property:
Property keys: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY and ChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
Property value: "true" or "false"

Selenium v4.8

      service.args << '--append-log'
      service.args << '--readable-timestamp'

Disabling build check

Chromedriver and Chrome browser versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Chrome. Note that this is an unsupported feature, and bugs will not be investigated.

Selenium v4.8

        String fileContent = new String(Files.readAllBytes(getLogLocation().toPath()));

Note: Java also allows disabling build checks by System Property:
Property key: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
Property value: "true" or "false"

            service.DisableBuildCheck = true;

Selenium v4.10

      service.args << '--disable-build-check'

Special Features

Casting

Pode comandar dispositivos Chrome Cast, incluindo partilhar abas

Condições de rede

Pode simular vários estados de rede (como exemplo, simular situações com pouca banda).

The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.

Logs

Permissões

DevTools

Veja a secção Chrome DevTools para mais informação em como usar Chrome DevTools