CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-selenium

Python bindings for Selenium WebDriver providing automated browser control for multiple browsers including Chrome, Firefox, Edge, Safari, and Internet Explorer

Pending
Overview
Eval results
Files

browser-configuration.mddocs/

Browser Configuration: Options, Service, and Proxy

This document covers browser configuration in Python Selenium WebDriver, including browser options, service configuration, and proxy settings. These configurations allow you to customize browser behavior, manage driver processes, and control network settings.

Browser Options Overview

Browser options allow you to configure browser behavior before launching. Each browser has its own options class that inherits from common base classes.

Common Base Classes

{ .api }

from selenium.webdriver.common.options import ArgOptions

class ArgOptions(BaseOptions):
    def __init__(self) -> None
    def add_argument(self, argument: str) -> None
    def add_extension(self, extension: str) -> None
    def add_encoded_extension(self, extension: str) -> None

Description: Base class for browser options that support arguments and extensions.

Chrome/Chromium Options

{ .api }

from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chromium.options import ChromiumOptions

class ChromiumOptions(ArgOptions):
    KEY = "goog:chromeOptions"
    
    def __init__(self) -> None

Description: Base class for Chromium-based browsers (Chrome, Edge) providing common functionality.

Binary Location

{ .api }

@property
def binary_location(self) -> str

@binary_location.setter
def binary_location(self, value: str) -> None

Description: The location of the browser binary.

Parameters:

  • value: Path to the browser executable

Example:

from selenium.webdriver.chrome.options import Options

options = Options()
options.binary_location = "/usr/bin/google-chrome-beta"
driver = webdriver.Chrome(options=options)

Extensions

{ .api }

@property
def extensions(self) -> List[str]

def add_extension(self, extension: str) -> None

def add_encoded_extension(self, extension: str) -> None

Description: Manage browser extensions.

Parameters:

  • extension: Path to .crx file or Base64 encoded extension data

Example:

options = Options()

# Add extension from file
options.add_extension("/path/to/extension.crx")

# Add extension from base64 encoded string
with open("/path/to/extension.crx", "rb") as f:
    encoded_extension = base64.b64encode(f.read()).decode('utf-8')
    options.add_encoded_extension(encoded_extension)

Experimental Options

{ .api }

@property
def experimental_options(self) -> dict

def add_experimental_option(self, name: str, value: Union[str, int, dict, List[str]]) -> None

Description: Add experimental Chrome options.

Parameters:

  • name: The experimental option name
  • value: The option value

Example:

options = Options()

# Enable Chrome DevTools Protocol
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])

# Set download preferences
prefs = {
    "download.default_directory": "/path/to/downloads",
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}
options.add_experimental_option("prefs", prefs)

# Enable logging
options.add_experimental_option("w3c", True)

Debugger Address

{ .api }

@property
def debugger_address(self) -> Optional[str]

@debugger_address.setter
def debugger_address(self, value: str) -> None

Description: Address of the remote devtools instance.

Parameters:

  • value: Address of remote devtools instance (hostname[:port])

Example:

options = Options()
options.debugger_address = "127.0.0.1:9222"

# Connect to existing Chrome instance
driver = webdriver.Chrome(options=options)

Common Chrome Arguments

Example:

options = Options()

# Headless mode
options.add_argument("--headless")

# Window size and position
options.add_argument("--window-size=1920,1080")
options.add_argument("--window-position=0,0")

# Disable features
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")

# User agent
options.add_argument("--user-agent=Custom User Agent String")

# Disable images for faster loading
options.add_argument("--blink-settings=imagesEnabled=false")

# Enable verbose logging
options.add_argument("--enable-logging")
options.add_argument("--log-level=0")

# Proxy
options.add_argument("--proxy-server=http://proxy.example.com:8080")

# Incognito mode
options.add_argument("--incognito")

# Disable notifications
options.add_argument("--disable-notifications")

Mobile Emulation

{ .api }

def enable_mobile(
    self,
    android_package: Optional[str] = "com.android.chrome",
    android_activity: Optional[str] = None,
    device_serial: Optional[str] = None,
) -> None

Description: Enable mobile emulation.

Parameters:

  • android_package: Android package name
  • android_activity: Android activity name
  • device_serial: Device serial number

Example:

options = Options()

# Mobile emulation with device metrics
mobile_emulation = {
    "deviceMetrics": {
        "width": 375,
        "height": 667,
        "pixelRatio": 2.0
    },
    "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) AppleWebKit/605.1.15"
}
options.add_experimental_option("mobileEmulation", mobile_emulation)

# Or use predefined device
mobile_emulation = {"deviceName": "iPhone X"}
options.add_experimental_option("mobileEmulation", mobile_emulation)

Firefox Options

{ .api }

from selenium.webdriver.firefox.options import Options as FirefoxOptions

class Options(ArgOptions):
    KEY = "moz:firefoxOptions"
    
    def __init__(self) -> None

Description: Firefox-specific browser options.

Binary Location

{ .api }

@property
def binary_location(self) -> str

@binary_location.setter
def binary_location(self, value: str) -> None

Description: Sets the location of the Firefox binary.

Example:

from selenium.webdriver.firefox.options import Options

options = Options()
options.binary_location = "/usr/bin/firefox-developer-edition"

Preferences

{ .api }

@property
def preferences(self) -> dict

def set_preference(self, name: str, value: Union[str, int, bool]) -> None

Description: Set Firefox preferences (about:config values).

Parameters:

  • name: Preference name
  • value: Preference value (string, integer, or boolean)

Example:

options = Options()

# Disable images
options.set_preference("permissions.default.image", 2)

# Set download directory
options.set_preference("browser.download.dir", "/path/to/downloads")
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")

# Disable geolocation
options.set_preference("geo.enabled", False)

# Set user agent
options.set_preference("general.useragent.override", "Custom User Agent")

# Enable/disable JavaScript
options.set_preference("javascript.enabled", True)

# Disable notifications
options.set_preference("dom.webnotifications.enabled", False)

Profile

{ .api }

@property
def profile(self) -> Optional[FirefoxProfile]

@profile.setter
def profile(self, new_profile: Union[str, FirefoxProfile]) -> None

Description: Set Firefox profile to use.

Parameters:

  • new_profile: Path to profile directory or FirefoxProfile object

Example:

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

# Create custom profile
profile = FirefoxProfile()
profile.set_preference("browser.download.dir", "/custom/download/path")
profile.set_preference("browser.download.folderList", 2)

options = Options()
options.profile = profile

# Or use existing profile directory
options.profile = "/path/to/existing/profile"

Logging

{ .api }

class Log:
    def __init__(self) -> None
    
    @property
    def level(self) -> Optional[str]
    
    @level.setter
    def level(self, value: str) -> None

Description: Configure Firefox logging.

Example:

options = Options()
options.log.level = "trace"  # trace, debug, config, info, warn, error, fatal

Firefox Arguments

Example:

options = Options()

# Headless mode
options.add_argument("--headless")

# Window size
options.add_argument("--width=1920")
options.add_argument("--height=1080")

# Private browsing
options.add_argument("--private")

# Safe mode
options.add_argument("--safe-mode")

# Profile directory
options.add_argument("--profile=/path/to/profile")

Edge Options

{ .api }

from selenium.webdriver.edge.options import Options as EdgeOptions

class Options(ChromiumOptions):
    @property
    def default_capabilities(self) -> dict

Description: Microsoft Edge options (inherits from ChromiumOptions).

Example:

from selenium.webdriver.edge.options import Options

options = Options()
options.add_argument("--headless")
options.add_argument("--disable-gpu")

# Edge-specific experimental options
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])

Safari Options

{ .api }

from selenium.webdriver.safari.options import Options as SafariOptions

class Options(BaseOptions):
    def __init__(self) -> None

Description: Safari browser options (limited configuration available).

Example:

from selenium.webdriver.safari.options import Options

options = Options()
# Safari has limited configuration options
driver = webdriver.Safari(options=options)

Service Configuration

Service objects manage the driver process (ChromeDriver, GeckoDriver, etc.).

{ .api }

from selenium.webdriver.common.service import Service

class Service(ABC):
    def __init__(
        self,
        executable_path: Optional[str] = None,
        port: int = 0,
        log_output: SubprocessStdAlias = None,
        env: Optional[Mapping[Any, Any]] = None,
        driver_path_env_key: Optional[str] = None,
        **kwargs,
    ) -> None

Description: Base class for all service objects that launch driver processes.

Parameters:

  • executable_path: Path to the driver executable
  • port: Port for the service to run on (0 = auto-assign)
  • log_output: Logging output configuration
  • env: Environment variables for the process
  • driver_path_env_key: Environment variable for driver path

Browser-Specific Services

Chrome Service

{ .api }

from selenium.webdriver.chrome.service import Service as ChromeService

class Service(ChromiumService):
    def __init__(
        self,
        executable_path: Optional[str] = None,
        port: int = 0,
        service_args: Optional[List[str]] = None,
        log_output: SubprocessStdAlias = None,
        env: Optional[Mapping[str, str]] = None,
        **kwargs,
    ) -> None

Example:

from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# Basic service
service = Service(executable_path="/path/to/chromedriver")

# Service with custom port and logging
service = Service(
    executable_path="/path/to/chromedriver",
    port=4444,
    service_args=["--verbose"],
    log_output="chromedriver.log"
)

options = Options()
driver = webdriver.Chrome(service=service, options=options)

Firefox Service

{ .api }

from selenium.webdriver.firefox.service import Service as FirefoxService

class Service(Service):
    def __init__(
        self,
        executable_path: Optional[str] = None,
        port: int = 0,
        service_args: Optional[List[str]] = None,
        log_output: SubprocessStdAlias = None,
        env: Optional[Mapping[str, str]] = None,
        **kwargs,
    ) -> None

Example:

from selenium.webdriver.firefox.service import Service

service = Service(
    executable_path="/path/to/geckodriver",
    log_output="geckodriver.log",
    service_args=["--log=trace"]
)

Service Methods

{ .api }

def start(self) -> None

Description: Starts the service.

Raises: WebDriverException if service cannot be started or connected to

{ .api }

def stop(self) -> None

Description: Stops the service.

{ .api }

def is_connectable(self) -> bool

Description: Check if the service is connectable.

Returns: True if service is accessible, False otherwise

{ .api }

@property
def service_url(self) -> str

Description: Gets the URL of the service.

Returns: Service URL (e.g., "http://localhost:4444")

Service Logging Configuration

Example:

import subprocess

# Log to file
service = Service(log_output="/path/to/driver.log")

# Log to stdout
service = Service(log_output=subprocess.STDOUT)

# Disable logging
service = Service(log_output=subprocess.DEVNULL)

# Log to custom file handle
with open("/path/to/custom.log", "w") as log_file:
    service = Service(log_output=log_file)

Proxy Configuration

{ .api }

from selenium.webdriver.common.proxy import Proxy, ProxyType

class Proxy:
    def __init__(self, raw: Optional[dict] = None) -> None

Description: Proxy configuration for WebDriver.

Proxy Types

{ .api }

class ProxyType:
    DIRECT = {"ff_value": 0, "string": "DIRECT"}
    MANUAL = {"ff_value": 1, "string": "MANUAL"}
    PAC = {"ff_value": 2, "string": "PAC"}
    AUTODETECT = {"ff_value": 4, "string": "AUTODETECT"}
    SYSTEM = {"ff_value": 5, "string": "SYSTEM"}
    UNSPECIFIED = {"ff_value": 6, "string": "UNSPECIFIED"}

Description: Set of possible proxy types.

Manual Proxy Configuration

{ .api }

@property
def http_proxy(self) -> str

@http_proxy.setter
def http_proxy(self, value: str) -> None

@property
def ssl_proxy(self) -> str

@ssl_proxy.setter
def ssl_proxy(self, value: str) -> None

@property
def ftp_proxy(self) -> str

@ftp_proxy.setter
def ftp_proxy(self, value: str) -> None

@property
def socks_proxy(self) -> str

@socks_proxy.setter
def socks_proxy(self, value: str) -> None

@property
def no_proxy(self) -> str

@no_proxy.setter
def no_proxy(self, value: str) -> None

Description: Manual proxy settings for different protocols.

SOCKS Proxy Authentication

{ .api }

@property
def socks_username(self) -> str

@socks_username.setter
def socks_username(self, value: str) -> None

@property
def socks_password(self) -> str

@socks_password.setter
def socks_password(self, value: str) -> None

@property
def socks_version(self) -> Optional[int]

@socks_version.setter
def socks_version(self, value: int) -> None

Description: SOCKS proxy authentication settings.

PAC (Proxy Auto-Configuration)

{ .api }

@property
def proxy_autoconfig_url(self) -> str

@proxy_autoconfig_url.setter
def proxy_autoconfig_url(self, value: str) -> None

Description: URL for proxy auto-configuration script.

Auto-Detection

{ .api }

@property
def auto_detect(self) -> bool

@auto_detect.setter
def auto_detect(self, value: bool) -> None

Description: Enable proxy auto-detection.

Proxy Examples

Manual HTTP Proxy:

from selenium.webdriver.common.proxy import Proxy, ProxyType

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "proxy.example.com:8080"
proxy.ssl_proxy = "proxy.example.com:8080"

# Apply to capabilities
capabilities = webdriver.DesiredCapabilities.CHROME.copy()
proxy.add_to_capabilities(capabilities)

driver = webdriver.Chrome(desired_capabilities=capabilities)

SOCKS Proxy with Authentication:

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.socks_proxy = "socks.proxy.com:1080"
proxy.socks_username = "username"
proxy.socks_password = "password"
proxy.socks_version = 5

PAC File Configuration:

proxy = Proxy()
proxy.proxy_type = ProxyType.PAC
proxy.proxy_autoconfig_url = "http://proxy.example.com/proxy.pac"

Auto-Detection:

proxy = Proxy()
proxy.proxy_type = ProxyType.AUTODETECT
proxy.auto_detect = True

No Proxy for Specific Domains:

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "proxy.example.com:8080"
proxy.no_proxy = "localhost,127.0.0.1,*.local,*.internal"

System Proxy:

proxy = Proxy()
proxy.proxy_type = ProxyType.SYSTEM

Complete Configuration Examples

Production Chrome Setup

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.proxy import Proxy, ProxyType

def create_production_chrome_driver():
    # Service configuration
    service = Service(
        executable_path="/usr/local/bin/chromedriver",
        port=4444,
        log_output="/var/log/chromedriver.log"
    )
    
    # Chrome options
    options = Options()
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=1920,1080")
    
    # Performance optimizations
    options.add_argument("--disable-extensions")
    options.add_argument("--disable-images")
    options.add_argument("--disable-plugins")
    options.add_argument("--disable-java")
    
    # Security
    options.add_argument("--disable-web-security")
    options.add_argument("--allow-running-insecure-content")
    
    # Download preferences
    prefs = {
        "profile.default_content_settings.popups": 0,
        "download.default_directory": "/tmp/downloads",
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.enabled": True
    }
    options.add_experimental_option("prefs", prefs)
    
    # Proxy configuration
    proxy = Proxy()
    proxy.proxy_type = ProxyType.MANUAL
    proxy.http_proxy = "corporate-proxy:8080"
    proxy.ssl_proxy = "corporate-proxy:8080"
    proxy.no_proxy = "localhost,127.0.0.1,*.internal"
    
    capabilities = options.to_capabilities()
    proxy.add_to_capabilities(capabilities)
    
    return webdriver.Chrome(
        service=service,
        options=options,
        desired_capabilities=capabilities
    )

Firefox Development Setup

from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

def create_firefox_dev_driver():
    # Profile setup
    profile = FirefoxProfile()
    
    # Developer preferences
    profile.set_preference("devtools.console.stdout.content", True)
    profile.set_preference("browser.cache.disk.enable", False)
    profile.set_preference("browser.cache.memory.enable", False)
    profile.set_preference("browser.cache.offline.enable", False)
    profile.set_preference("network.http.use-cache", False)
    
    # Download preferences
    profile.set_preference("browser.download.dir", "/tmp/firefox-downloads")
    profile.set_preference("browser.download.folderList", 2)
    profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 
                         "application/pdf,text/csv,application/zip")
    
    # Service configuration
    service = Service(
        executable_path="/usr/local/bin/geckodriver",
        log_output="/var/log/geckodriver.log",
        service_args=["--log=debug"]
    )
    
    # Options
    options = Options()
    options.profile = profile
    options.add_argument("--width=1920")
    options.add_argument("--height=1080")
    
    # Development logging
    options.log.level = "trace"
    
    return webdriver.Firefox(service=service, options=options)

Mobile Testing Configuration

def create_mobile_chrome_driver():
    options = Options()
    
    # Mobile emulation
    mobile_emulation = {
        "deviceMetrics": {
            "width": 375,
            "height": 812,
            "pixelRatio": 3.0
        },
        "userAgent": (
            "Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) "
            "AppleWebKit/605.1.15 (KHTML, like Gecko) "
            "Version/13.0 Mobile/15E148 Safari/604.1"
        )
    }
    options.add_experimental_option("mobileEmulation", mobile_emulation)
    
    # Touch events
    options.add_argument("--touch-events")
    
    return webdriver.Chrome(options=options)

Headless Testing with Custom User Agent

def create_headless_driver_with_stealth():
    options = Options()
    
    # Headless mode
    options.add_argument("--headless")
    options.add_argument("--window-size=1920,1080")
    
    # Stealth mode to avoid detection
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)
    
    # Custom user agent
    user_agent = (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/91.0.4472.124 Safari/537.36"
    )
    options.add_argument(f"--user-agent={user_agent}")
    
    # Additional stealth options
    prefs = {
        "profile.default_content_setting_values.notifications": 2,
        "profile.default_content_settings.popups": 0,
        "profile.managed_default_content_settings.images": 2
    }
    options.add_experimental_option("prefs", prefs)
    
    driver = webdriver.Chrome(options=options)
    
    # Execute script to remove webdriver property
    driver.execute_script(
        "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
    )
    
    return driver

This comprehensive guide covers all aspects of browser configuration in Selenium WebDriver, enabling you to customize browser behavior, manage driver processes, and configure network settings for your specific testing needs.

Install with Tessl CLI

npx tessl i tessl/pypi-selenium

docs

action-chains.md

browser-configuration.md

element-interaction.md

index.md

waits-conditions.md

webdriver-classes.md

tile.json