Как изменить настройки браузера selenium

These capabilities are shared by all browsers.

These capabilities are shared by all browsers.

In Selenium 3, capabilities were defined in a session by using Desired Capabilities classes.
As of Selenium 4, you must use the browser options classes.
For remote driver sessions, a browser options instance is required as it determines which browser will be used.

These options are described in the w3c specification for Capabilities.

Each browser has custom options that may be defined in addition to the ones defined in the specification.

browserName

This capability is used to set the browserName for a given session.
If the specified browser is not installed at the
remote end, the session creation will fail.

browserVersion

This capability is optional, this is used to
set the available browser version at remote end.
For Example, if ask for Chrome version 75 on a system that
only has 80 installed, the session creation will fail.

pageLoadStrategy

Three types of page load strategies are available.

The page load strategy queries the
document.readyState
as described in the table below:

Strategy Ready State Notes
normal complete Used by default, waits for all resources to download
eager interactive DOM access is ready, but other resources like images may still be loading
none Any Does not block WebDriver at all

The document.readyState property of a document describes the loading state of the current document.

When navigating to a new page via URL, by default, WebDriver will hold off on completing a navigation
method (e.g., driver.navigate().get()) until the document ready state is complete. This does not
necessarily mean that the page has finished loading
, especially for sites like Single Page Applications
that use JavaScript to dynamically load content after the Ready State returns complete. Note also
that this behavior does not apply to navigation that is a result of clicking an element or submitting a form.

If a page takes a long time to load as a result of downloading assets (e.g., images, css, js)
that aren’t important to the automation, you can change from the default parameter of normal to
eager or none to speed up the session. This value applies to the entire session, so make sure
that your waiting strategy is sufficient to minimize
flakiness.

normal (default)

WebDriver waits until the load
event fire is returned.

  • Java
  • Python
  • CSharp
  • Ruby
  • JavaScript
  • Kotlin
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;

public class pageLoadStrategy {
  public static void main(String[] args) {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
    WebDriver driver = new ChromeDriver(chromeOptions);
    try {
      // Navigate to Url
      driver.get("https://google.com");
    } finally {
      driver.quit();
    }
  }
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'normal'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
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();
      }
    }
  }
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :normal

driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
    it('Navigate using normal page loading strategy', async function () {
      let driver = await env
        .builder()
        .setChromeOptions(options.setPageLoadStrategy('normal'))
        .build();

      await driver.get('https://www.google.com');
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.

  • Java
  • Python
  • CSharp
  • Ruby
  • JavaScript
  • Kotlin
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;

public class pageLoadStrategy {
  public static void main(String[] args) {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
    WebDriver driver = new ChromeDriver(chromeOptions);
    try {
      // Navigate to Url
      driver.get("https://google.com");
    } finally {
      driver.quit();
    }
  }
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
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();
      }
    }
  }
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :eager

driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
    it('Navigate using eager page loading strategy', async function () {
      let driver = await env
        .builder()
        .setChromeOptions(options.setPageLoadStrategy('eager'))
        .build();

      await driver.get('https://www.google.com');
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.

  • Java
  • Python
  • CSharp
  • Ruby
  • JavaScript
  • Kotlin
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;

public class pageLoadStrategy {
  public static void main(String[] args) {
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
    WebDriver driver = new ChromeDriver(chromeOptions);
    try {
      // Navigate to Url
      driver.get("https://google.com");
    } finally {
      driver.quit();
    }
  }
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'none'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
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();
      }
    }
  }
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :none

driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
    it('Navigate using none page loading strategy', async function () {
      let driver = await env
        .builder()
        .setChromeOptions(options.setPageLoadStrategy('none'))
        .build();

      await driver.get('https://www.google.com');
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.

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.

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.

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.

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.

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

setWindowRect

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

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.

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:

  • Java
  • Python
  • CSharp
  • Ruby
  • JavaScript
  • Kotlin
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();
}
}
from selenium import webdriver

PROXY = "<HOST:PORT>"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy": PROXY,
"ftpProxy": PROXY,
"sslProxy": PROXY,
"proxyType": "MANUAL",

}

with webdriver.Firefox() as driver:
driver.get("https://selenium.dev")
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/");
}
}
proxy = Selenium::WebDriver::Proxy.new(http: '<HOST:PORT>')
cap   = Selenium::WebDriver::Remote::Capabilities.chrome(proxy: proxy)

driver = Selenium::WebDriver.for(:chrome, capabilities: cap)
driver.get('http://google.com')
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()
    }
}

Support the Selenium Project

Want to support the Selenium project? Learn more or view the full list of sponsors.

Here is firefox profile default prefs from python selenium 2.31.0 firefox_profile.py

and type «about:config» in firefox address bar to see all prefs

reference to the entries in about:config: http://kb.mozillazine.org/About:config_entries

DEFAULT_PREFERENCES = {
    "app.update.auto": "false",
    "app.update.enabled": "false",
    "browser.download.manager.showWhenStarting": "false",
    "browser.EULA.override": "true",
    "browser.EULA.3.accepted": "true",
    "browser.link.open_external": "2",
    "browser.link.open_newwindow": "2",
    "browser.offline": "false",
    "browser.safebrowsing.enabled": "false",
    "browser.search.update": "false",
    "extensions.blocklist.enabled": "false",
    "browser.sessionstore.resume_from_crash": "false",
    "browser.shell.checkDefaultBrowser": "false",
    "browser.tabs.warnOnClose": "false",
    "browser.tabs.warnOnOpen": "false",
    "browser.startup.page": "0",
    "browser.safebrowsing.malware.enabled": "false",
    "startup.homepage_welcome_url": ""about:blank"",
    "devtools.errorconsole.enabled": "true",
    "dom.disable_open_during_load": "false",
    "extensions.autoDisableScopes" : 10,
    "extensions.logging.enabled": "true",
    "extensions.update.enabled": "false",
    "extensions.update.notifyUser": "false",
    "network.manage-offline-status": "false",
    "network.http.max-connections-per-server": "10",
    "network.http.phishy-userpass-length": "255",
    "offline-apps.allow_by_default": "true",
    "prompts.tab_modal.enabled": "false",
    "security.fileuri.origin_policy": "3",
    "security.fileuri.strict_origin_policy": "false",
    "security.warn_entering_secure": "false",
    "security.warn_entering_secure.show_once": "false",
    "security.warn_entering_weak": "false",
    "security.warn_entering_weak.show_once": "false",
    "security.warn_leaving_secure": "false",
    "security.warn_leaving_secure.show_once": "false",
    "security.warn_submit_insecure": "false",
    "security.warn_viewing_mixed": "false",
    "security.warn_viewing_mixed.show_once": "false",
    "signon.rememberSignons": "false",
    "toolkit.networkmanager.disable": "true",
    "toolkit.telemetry.enabled": "false",
    "toolkit.telemetry.prompted": "2",
    "toolkit.telemetry.rejected": "true",
    "javascript.options.showInConsole": "true",
    "browser.dom.window.dump.enabled": "true",
    "webdriver_accept_untrusted_certs": "true",
    "webdriver_enable_native_events": "true",
    "webdriver_assume_untrusted_issuer": "true",
    "dom.max_script_run_time": "30",
    }

Here is firefox profile default prefs from python selenium 2.31.0 firefox_profile.py

and type «about:config» in firefox address bar to see all prefs

reference to the entries in about:config: http://kb.mozillazine.org/About:config_entries

DEFAULT_PREFERENCES = {
    "app.update.auto": "false",
    "app.update.enabled": "false",
    "browser.download.manager.showWhenStarting": "false",
    "browser.EULA.override": "true",
    "browser.EULA.3.accepted": "true",
    "browser.link.open_external": "2",
    "browser.link.open_newwindow": "2",
    "browser.offline": "false",
    "browser.safebrowsing.enabled": "false",
    "browser.search.update": "false",
    "extensions.blocklist.enabled": "false",
    "browser.sessionstore.resume_from_crash": "false",
    "browser.shell.checkDefaultBrowser": "false",
    "browser.tabs.warnOnClose": "false",
    "browser.tabs.warnOnOpen": "false",
    "browser.startup.page": "0",
    "browser.safebrowsing.malware.enabled": "false",
    "startup.homepage_welcome_url": ""about:blank"",
    "devtools.errorconsole.enabled": "true",
    "dom.disable_open_during_load": "false",
    "extensions.autoDisableScopes" : 10,
    "extensions.logging.enabled": "true",
    "extensions.update.enabled": "false",
    "extensions.update.notifyUser": "false",
    "network.manage-offline-status": "false",
    "network.http.max-connections-per-server": "10",
    "network.http.phishy-userpass-length": "255",
    "offline-apps.allow_by_default": "true",
    "prompts.tab_modal.enabled": "false",
    "security.fileuri.origin_policy": "3",
    "security.fileuri.strict_origin_policy": "false",
    "security.warn_entering_secure": "false",
    "security.warn_entering_secure.show_once": "false",
    "security.warn_entering_weak": "false",
    "security.warn_entering_weak.show_once": "false",
    "security.warn_leaving_secure": "false",
    "security.warn_leaving_secure.show_once": "false",
    "security.warn_submit_insecure": "false",
    "security.warn_viewing_mixed": "false",
    "security.warn_viewing_mixed.show_once": "false",
    "signon.rememberSignons": "false",
    "toolkit.networkmanager.disable": "true",
    "toolkit.telemetry.enabled": "false",
    "toolkit.telemetry.prompted": "2",
    "toolkit.telemetry.rejected": "true",
    "javascript.options.showInConsole": "true",
    "browser.dom.window.dump.enabled": "true",
    "webdriver_accept_untrusted_certs": "true",
    "webdriver_enable_native_events": "true",
    "webdriver_assume_untrusted_issuer": "true",
    "dom.max_script_run_time": "30",
    }

This tutorial is in continuation to our previous tutorial which is on use of DesiredCapabilities in Selenium WebDriver to set the browser’s properties. The Desired Capabilities class is not used anymore to handle the browser’s properties in Selenium which is most probably due to change in the architecture of the latest versions of the browsers. If you want to set the capability properties for your browser then you need to use browser specific options properties, that is why today we are going to discuss the ChromeOptions class of Selenium remote library.

Let’s start today with the options properties for chrome, further, we will discuss remaining browser options class for the rest of the web browsers in subsequent tutorials.

When we use DesiredCapabilities class to handle the browser-based session (say Chrome here) then it underlines the ChromeDriver() which indicates that it has been deprecated in Java programming language. However, it is available to use in Python, Ruby and other programming languages. See image below:

ChromeOptions alternative to DesiredCapabilitiesWhat is ChromeOptions in Selenium WebDriver?

ChromeOptions is a class in Selenium which is used to set the capability and customization and configuration of the ChromeDriver session as well.  This class inherits the MutableCapabilities class. Here is the library path:

org.openqa.selenium.MutableCapabilities

Click here to know more about it.

MutableCapabilities class first came in existence with Selenium 3.6.0 and now all the options classes for respective browsers extends this class in Java. We need to import below package to work with Chrome Options in Java to customize the Chrome sessions.

import org.openqa.selenium.chrome.ChromeOptions;

What are the uses of ChromeOptions in Selenium?

ChromeOptions has all the uses which DesiredCapabilities was doing, but, it is only dedicated to one browser. Let’s have a look over some of the uses of the Chrome Options.

  • It is used to get and set capabilities in Chrome
  • Chrome Options supports to add the extension to the browser at runtime
  • It helps to add binary at runtime
  • ChromeOptions is used to handle the proxy while running test automation
  • We use ChromeOptions in Selenium Grid to remotely set the Chrome session in node machines

We will further discuss the implementation of the above uses in a separate article at inviul.com.

Methods of ChromeOptions class

Here is the list of some of the methods of the ChromeOptions class which we use them whenever required as per the criteria.

  • addArguments(arguments)
  • addEncodedExtensions()
  • addExtensions()
  • getCapability()
  • setCapability()
  • getPlatform()
  • setAcceptInsecureCerts()
  • setBinary()
  • setProxy()
  • setExperiementalOption()
  • setPageLoadStrategy()
  • setUnhandledPromptBehaviour()
  • getBrowserName()
  • getVersion()

How to set capability with ChromeOptions in Selenium WebDriver?

Following program uses Chrome Options class to set the capability to the ChromeDriver. Here we are setting browser name and Windows 10 as the platform with the help of Chrome options. Further, we set the instance of ChromeOptions as the argument in ChromeDriver().

Let’s have an eye to the programming part.

package Test;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;

public class ChromeOptionsDesiredCapabilitiesDemo {

	public static void main(String[] args) {
		
		ChromeOptions option = new ChromeOptions();
				
		option.setCapability(CapabilityType.BROWSER_NAME, "CHROME");
		
		option.setCapability(CapabilityType.PLATFORM, Platform.WIN10);
		
		System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe");	
		 
		WebDriver  driver  = new ChromeDriver(option);
		
		 driver.get("https://www.inviul.com/");
	  	  
	  	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		  
	  	  driver.manage().window().maximize();
	  	  
	  	  System.out.println("Platform is- "+option.getPlatform());
	  	 System.out.println(driver.getTitle());
	  	 
	  	 driver.close();
	  	 
	  	 driver.quit();
		

	}

}

This was all about setting ChromeOptions as the capability in Selenium WebDriver. If you have any queries, suggestions or feedback then feel free to write below in the comment form and don’t miss to join our Facebook group for quick and latest updates on Selenium WebDriver and Automation testing as well.

Join Inviul fb group

About The Author

Avinash Mishra

Avinash Mishra is the author of Inviul blog. He is a software engineer and blogger by choice. He loves to write blogs, and apart from blogging, he is interested in documentary film making, listening to music, traveling around the world and philanthropic activities.

1. Справочная информация

При использовании технологии рендеринга в браузере selenium для сканирования информации на сайте по умолчанию это обычный браузер с чистым Chrome, и мы обычно добавляем некоторые плагины, расширения, агенты и другие приложения при использовании браузера. Соответственно, когда мы используем браузер Chrome для сканирования веб-сайта, нам может потребоваться выполнить специальную настройку для этого хрома, чтобы он соответствовал поведению сканера.
Обычно используемые поведения:
Запретить загрузку изображений и видео. Увеличьте скорость загрузки веб-страниц.
Добавить прокси: технология защиты от лазания, используемая для доступа к определенным страницам через стену или реагирования на ограничения частоты доступа по IP.
Использовать мобильную голову: зайдите на мобильный сайт, как правило, технология против скалолазания на этом сайте относительно слаба.
Добавить расширения: функционирует как обычный браузер.
Установите код: ответьте на китайскую станцию, чтобы предотвратить искажение символов.
Блокировать выполнение JavaScript.
        ………

2. Окружающая среда

    python 3.6.1
Система: win7
    IDE:pycharm
Установили браузер Chrome
Хромированный драйвер настроен
    selenium 3.7.0

3. chromeOptions

ChromeOptions — это класс, который настраивает запуск Chrome как атрибут. С помощью этого класса мы можем настроить следующие параметры для Chrome (эту часть можно увидеть через исходный код селена):
Установить местоположение двоичного файла Chrome (binary_location)
Добавить параметры запуска (add_argument)
Добавить приложение расширения (add_extension, add_encoded_extension)
Добавить параметры экспериментальной настройки (add_experimental_option)
Установить адрес отладчика (debugger_address)

Исходный код:

# .Libsite-packagesseleniumwebdriverchromeoptions.py
class Options(object):

   def __init__(self):
                 # Установить местоположение двоичного файла Chrome
        self._binary_location = ''
                 # Добавить параметры запуска
        self._arguments = []
                 # Добавить расширенное приложение
        self._extension_files = []
        self._extensions = []
                 # Добавить параметры экспериментальной настройки
        self._experimental_options = {}
                 # Установить адрес отладчика
        self._debugger_address = None

Варианты использования:

# Установите кодировку по умолчанию в utf-8, что на китайском

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('lang=zh_CN.UTF-8')
driver = webdriver.Chrome(chrome_options = options)

4. Общая конфигурация

Официальная ссылка на сайт: https://sites.google.com/a/chromium.org/chromedriver/capabilities

4.1 Установить формат кодировки

# Установите кодировку по умолчанию в utf-8, что на китайском

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('lang=zh_CN.UTF-8')
driver = webdriver.Chrome(chrome_options = options)

4.2 Моделирование мобильных устройств

Форма агента пользователя мобильного устройства: http://www.fynas.com/ua
Поскольку способность мобильной версии веб-сайта сканировать является относительно слабой # Установив пользовательский агент, он используется для имитации мобильных устройств.

# Например для симуляции браузера Android QQ
options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')

 # Имитация iPhone 6
options.add_argument('user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"')

4.3 Запретить загрузку изображений

Это может увеличить скорость сканирования без загрузки изображений.

# Отключить загрузку картинок
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)

 # Запустите браузер и установите ожидание
browser = webdriver.Chrome(chrome_options=chrome_options)
 browser.set_window_size (configure.windowHeight, configure.windowWidth) # В соответствии с разрешением рабочего стола, главным образом для захвата скриншота кода проверки
wait = WebDriverWait(browser, timeout = configure.timeoutMain)

4.4 Добавить агента

Добавьте прокси-сервер для искателя селена. В этом месте особенно важно отметить, что при выборе прокси-сервера старайтесь выбирать статический IP-адрес, чтобы повысить стабильность сканирования. Потому что если вы выбираете селен в качестве сканера, это означает, что антискользящая способность веб-сайта относительно высока (в противном случае он находится прямо на скрапе), и у него более высокий контроль согласованности между веб-страницами, файлами cookie и статусом пользователя. Если вы используете динамический анонимный IP, время выживания каждого IP будет очень коротким (1 ~ 3 минуты).

from selenium import webdriver
 # Статический IP: 102.23.1.105: 2005
 # Динамический IP-адрес Абуюна: http: // D37EPSERV96VT4W2: [email protected]: 9020
PROXY = "proxy_host:proxy:port"
options = webdriver.ChromeOptions()
desired_capabilities = options.to_capabilities()
desired_capabilities['proxy'] = {
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "noProxy": None,
    "proxyType": "MANUAL",
    "class": "org.openqa.selenium.Proxy",
    "autodetect": False
}
driver = webdriver.Chrome(desired_capabilities = desired_capabilities)

4.5 Настройки параметров браузера

Обычно Selenium открывает чистый браузер без расширений, но иногда мы хотим установить в браузере некоторые настройки, например, установить значение по умолчанию для параметра flash, чтобы всегда разрешать глобальное удаление файлов cookie, очистку кешей и тому подобное.
Для достижения этой цели существует способ мышления. В качестве примера ниже приводится браузер Chrome:
Когда запускается искатель селена, сначала откройте окно, введите в адресную строку: chrome: // settings / content или chrome: // settings / privacy, а затем программу, как в обычном веб-приложении. Аналогично, установите и сохраните.
Напишите описание изображения здесь

4.6. Добавить приложение для расширения браузера

Обычно Selenium открывает чистый браузер без расширений, но иногда нам нужно использовать некоторые плагины для обхода данных, такие как класс синтаксического анализа xpath helper, класс перевода и получение дополнительной информации (продажи). Итак, как мы можем добавить некоторые плагины, которые нам нужны, когда мы запускаем chromedriver?

Ниже приведен пример загрузки подключаемого модуля Xpath Helper в Chrome:

4.6.1. Скачать соответствующий плагин

Адрес для загрузки Xpath Helper: http://download.csdn.net/download/gengliang123/9944202
Ниже приведен файл с суффиксом crx:
Напишите описание изображения здесь

4.6.2 Заполните путь к плагину в коде

# Добавить приложение-помощник xpath

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()

 # Настройте расширение приложения
extension_path = 'D:/extension/XPath-Helper_v2.0.2.crx'
chrome_options.add_extension(extension_path)

 # Запустите браузер и установите ожидание
browser = webdriver.Chrome(chrome_options=chrome_options)

4.6.3 Отображение результатов

Напишите описание изображения здесь
4.6.4. Примечания

Во-первых, чтобы увеличить скорость сканирования, загрузите как можно меньше плагинов.
Во-вторых, существует схема, которая загружает всю информацию о конфигурации пользователя в браузер Chrome, но тест недоступен, как показано ниже:
Справочная статья: http://blog.csdn.net/y100100/article/details/44061469
Справочная статья: https://www.cnblogs.com/stonewang313/p/3938488.html
Справочная статья: http://blog.csdn.net/liaojianqiu0115/article/details/78353267
Сначала введите C: Users (пользователь) имя вашего компьютера AppData Local Google Chrome User Data Default Extensions, нажмите Extensions, папка внутри — это установка Расширение (не забудьте сначала отобразить скрытую папку на компьютере, иначе вы ее не найдете) Но название — это набор неупорядоченных английских букв, которые я не понимаю. , Найдите номер версии в опции Chrome Extensions и упакуйте нужный вам плагин: откройте настройки Chrome, нажмите на расширение в нем, выберите режим разработчика, под установленным вами плагином появится идентификатор, этот идентификатор соответствует вам Плагин, который нужно упаковать, затем упаковать расширение, найти папку с номером версии в соответствующей папке (или вы также можете скопировать эту папку в любое место на компьютере), то есть в папку внутри папки с именем ID Затем нажмите на расширение пакета, и оно появится соответственно. Файлы с суффиксными именами crx и pem появятся на том же уровне номера версии. Этот файл crx Это то, что нам нужно (однако, таким образом, я не могу найти такой файл crx в своем локальном каталоге, мне нужно скачать его отдельно …). Подготовка завершена, см. Код:

# Первый способ
 # Расширения браузера chrome находятся в: C:  Users  Администратор  AppData  Local  Google  Chrome  Данные пользователя  Профиль 2  Расширения 
chrome_options.add_argument("user-data-dir=C:/Users/Administrator/AppData/Local/Google/Chrome/User Data")

# Загрузите все конфигурации Chrome, введите chrome: // version / в адресную строку Chrome, просмотрите «путь к профилю», а затем вызовите этот файл конфигурации при запуске браузера, код выглядит следующим образом:
 

from selenium import webdriver
option = webdriver.ChromeOptions()
 option.add_argument ('-user-data-dir = C:  Users  Администратор  AppData  Local  Google  Chrome  User Data') # Установить в собственный каталог данных пользователя
driver = webdriver.Chrome(chrome_options=option)

# Неверный результат
Во-первых, все окна браузера, включая те, которые открыты сами по себе, будут контролироваться.
Во-вторых, другие действия не будут работать и завершатся сбоем.
 

Traceback (most recent call last):
  File "E:/PyCharmCode/taobaoProductSelenium/taobaoSelenium.py", line 40, in <module>
         # Запустите браузер и установите ожидание
  File "E:Minicondalibsite-packagesseleniumwebdriverchromewebdriver.py", line 69, in __init__
    desired_capabilities=desired_capabilities)
  File "E:Minicondalibsite-packagesseleniumwebdriverremotewebdriver.py", line 151, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "E:Minicondalibsite-packagesseleniumwebdriverremotewebdriver.py", line 240, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "E:Minicondalibsite-packagesseleniumwebdriverremotewebdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "E:Minicondalibsite-packagesseleniumwebdriverremoteerrorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT 6.1.7601 SP1 x86_64)

5. Другие параметры

Справочная статья: http://blog.csdn.net/liaojianqiu0115/article/details/78353267

5.1 Команды адресной строки Chrome

Введите следующую команду в адресной строке браузера Chrome, и соответствующий результат будет возвращен. Эти команды включают в себя просмотр состояния памяти, состояния браузера, состояния сети, состояния DNS-сервера, кеша подключаемых модулей и т. Д. Однако следует отметить, что эти команды постоянно меняются, поэтому их не обязательно легко использовать.
about: version — отображает текущую версию
about: memory — отображает использование памяти локальным браузером
about: plugins-отображает установленные плагины
about: история отображения гистограмм
about: dns-отображает статус DNS
about: кэш-страница отображения кеша
about: gpu-есть ли аппаратное ускорение
О файле: flags-Open Некоторые плагины // После использования что-то всплывает: «Пожалуйста, будьте осторожны, эти эксперименты могут быть рискованными», интересно, если я испорчу свою конфигурацию!
chrome: // extensions / -Просмотреть установленные расширения
   

5.2 Практические параметры Chrome

Некоторые другие практические параметры о Chrome и краткие китайские инструкции, способ использования такой же, как и выше 4.5.4, конечно, его также можно использовать в оболочке.
   

–User-data-dir = ”[PATH]” Укажите путь к пользовательским данным в папке пользователя. Пользовательские данные, такие как закладки, можно сохранить в разделе, отличном от системного раздела.
         --Disk-cache-dir = "" PATH "" Указать путь к кешу
         --Disk-cache-size = указать размер кэша, единица измерения - байт
         –Первый запуск сброса в исходное состояние, запуск в первый раз
         - Инкогнито старт в режиме инкогнито
         --Disable-javascript отключить Javascript
         –Omnibox-popup-count = ”num” Изменить количество меню подсказок, отображаемых в адресной строке, на num. Я изменился на 15.
         –User-agent = ”xxxxxxxx” Измените строку агента в заголовке HTTP-запроса, вы можете просмотреть эффект модификации на странице about: version
         - Disable-plugins запрещает загрузку всех плагинов, что может увеличить скорость. Вы можете проверить эффект на странице about: plugins
         --Disable-javascript Отключите JavaScript, добавьте это, если вы чувствуете себя медленно
         -Disable-Java отключить Java
         - Старт-максимизировать максимизировать при запуске
         - Песочница не отменяет режим песочницы
         - Однопроцессный запущенный процесс
         - Process-per-tab использовать отдельный процесс для каждой вкладки
         - Process-per-site Используйте отдельный процесс для каждого сайта
         - Плагин In-process-plugins не включает отдельные процессы
         --Disable-popup-blocking отключить блокировку всплывающих окон
         --Disable-плагины отключают плагины
         --Disable-изображения отключают изображения
         - Инкогнито загрузки в режиме инкогнито
         --Enable-UDD-профили включить меню переключения учетной записи
         - Proxy-pac-url использовать pac proxy [через 1/2]
         --Lang = zh-CN Установить язык для упрощенного китайского
         --Disk-cache-dir пользовательский каталог кеша
         - Максимальный размер кэша диска в размере диска (в байтах)
         Максимальный размер кэша мультимедийного кэша (в байтах)
         - Bookmark-menu добавить кнопку закладки на панель инструментов
         - Включить-синхронизировать включить синхронизацию закладок
         - Однопроцессный процесс под управлением Google Chrome
         - Начните с максимального запуска Google Chrome, чтобы увеличить
         --Disable-Java Отключить Java
         - Песочница не работает в режиме без песочницы

Источник: CSDN
Оригинал: https://blog.csdn.net/zwq912318834/article/details/78933910
 

Table of Contents

Hide

  1. What are Chrome Options in Selenium WebDriver?
  2. Chrome Options for Selenium WebDriver
    1. Starting Chrome in maximized mode
    2. Starting Chrome in Incognito mode
    3. Starting Chrome in Headless mode
    4. Disable All Extensions on Chrome Browser Instance
    5. Disable pop-ups on Chrome Browser Instance
    6. Changing the File Download Path

What are Chrome Options in Selenium WebDriver?

ChromeOptions options = new ChromeOptions()
options.addArgument("start-maximized");
ChromeDriver driver = new ChromeDriver(options);

Although there are a lot of arguments available in ChromeOptions class, we will be looking into most commonly used in Selenium WebDriver.

While using Chrome Driver with Selenium to automate test scripts, there could be instances where we need to alter the browser settings to achieve certain behaviors. Selenium WebDriver uses Chrome Options Class to manipulate several properties of Chrome Browser.

To understand, Let’s consider a scenario where you want to download files to the project directory during the test script execution? Or if you’re going to execute tests in incognito mode? Chrome Options Class will help us achieve this.

Example:

The below example shows the method to instantiate & implement Chrome Options with Chrome Driver. The case depicts the property to launch a chrome browser in maximized mode.

Chrome Options for Selenium WebDriver

Starting Chrome in maximized mode

Chrome Options for running Chrome browser in maximized mode can be accomplished by using the predefined arguments maximized-mode. The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class T5_ChromeOptions {
    @Test
    public void TC1_MaximizedMode() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}
Starting Chrome in Incognito mode

Chrome Options for running Chrome browser in Incognito mode can be accomplished by using the predefined arguments incognito. The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class T5_ChromeOptions {
    @Test
    public void TC2_IncognitoMode() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("incognito");
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}
Starting Chrome in Headless mode

A Headless browser runs in the background. You will not see the browser GUI or the operations been operated on it. Chrome Options for running Chrome browser in Headless mode can be accomplished by using the predefined arguments headless.

The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class T5_ChromeOptions {
    @Test
    public void TC3_HeadlessMode() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}
Disable All Extensions on Chrome Browser Instance

It might be required to disable existing extensions for Test Script execution. The chrome browser can be launched with all existing extensions disabled using the predefined disable-extensions argument.

The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class T5_ChromeOptions {
    @Test
    public void TC4_DisabledExtensions() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-extensions");
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}

One of the common problems faced during execution is when the selenium test cases fail due to a notification popup displayed by the browser. It can be taken care of by setting the disable-popup-blocking argument in Chrome Options.

The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class T5_ChromeOptions {
    @Test
    public void TC5_DisablePopups() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-popup-blocking");
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}
Changing the File Download Path

Whenever you download a file, it gets downloaded in the default download directory. While running the selenium test, it may be required to download a file through automation script and verify the download. In such cases, we need to download the file in a folder where you can verify the same seamlessly. This can be achieved using download.default_directory Experimental Option in Chrome Options.

The sample code to accomplish it is mentioned below.

package tutorials;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class T5_ChromeOptions {
    @Test
    public void TC6_DownloadPathSettings() {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
      
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory",
                System.getProperty("user.dir") + File.separator + "downlods");
         
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
       
        WebDriver driver = new ChromeDriver(options);
        driver.get("https://automationbyte.com");
        
        String title = driver.getTitle();
        System.out.println("Website Title: " + title);
        
        driver.quit();
    }
}

I am a tech enthusiast and a workaholic guy currently working as an Automation Engineer in Telecom Domain. Over the past couple of years, I have explored various Automation Tools that can serve today’s business needs.

Понравилась статья? Поделить с друзьями:
  • Как изменить настройки брандмауэра windows 10 для снятия блокировки
  • Как изменить настройки блокировки экрана на компьютере
  • Как изменить настройки безопасности сети
  • Как изменить настройки безопасности роутера
  • Как изменить настройки безопасности папки