Python bindings for Selenium WebDriver providing automated browser control for multiple browsers including Chrome, Firefox, Edge, Safari, and Internet Explorer
—
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 allow you to configure browser behavior before launching. Each browser has its own options class that inherits from 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) -> NoneDescription: Base class for browser options that support arguments and extensions.
{ .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) -> NoneDescription: Base class for Chromium-based browsers (Chrome, Edge) providing common functionality.
{ .api }
@property
def binary_location(self) -> str
@binary_location.setter
def binary_location(self, value: str) -> NoneDescription: The location of the browser binary.
Parameters:
value: Path to the browser executableExample:
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = "/usr/bin/google-chrome-beta"
driver = webdriver.Chrome(options=options){ .api }
@property
def extensions(self) -> List[str]
def add_extension(self, extension: str) -> None
def add_encoded_extension(self, extension: str) -> NoneDescription: Manage browser extensions.
Parameters:
extension: Path to .crx file or Base64 encoded extension dataExample:
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){ .api }
@property
def experimental_options(self) -> dict
def add_experimental_option(self, name: str, value: Union[str, int, dict, List[str]]) -> NoneDescription: Add experimental Chrome options.
Parameters:
name: The experimental option namevalue: The option valueExample:
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){ .api }
@property
def debugger_address(self) -> Optional[str]
@debugger_address.setter
def debugger_address(self, value: str) -> NoneDescription: 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)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"){ .api }
def enable_mobile(
self,
android_package: Optional[str] = "com.android.chrome",
android_activity: Optional[str] = None,
device_serial: Optional[str] = None,
) -> NoneDescription: Enable mobile emulation.
Parameters:
android_package: Android package nameandroid_activity: Android activity namedevice_serial: Device serial numberExample:
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){ .api }
from selenium.webdriver.firefox.options import Options as FirefoxOptions
class Options(ArgOptions):
KEY = "moz:firefoxOptions"
def __init__(self) -> NoneDescription: Firefox-specific browser options.
{ .api }
@property
def binary_location(self) -> str
@binary_location.setter
def binary_location(self, value: str) -> NoneDescription: 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"{ .api }
@property
def preferences(self) -> dict
def set_preference(self, name: str, value: Union[str, int, bool]) -> NoneDescription: Set Firefox preferences (about:config values).
Parameters:
name: Preference namevalue: 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){ .api }
@property
def profile(self) -> Optional[FirefoxProfile]
@profile.setter
def profile(self, new_profile: Union[str, FirefoxProfile]) -> NoneDescription: Set Firefox profile to use.
Parameters:
new_profile: Path to profile directory or FirefoxProfile objectExample:
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"{ .api }
class Log:
def __init__(self) -> None
@property
def level(self) -> Optional[str]
@level.setter
def level(self, value: str) -> NoneDescription: Configure Firefox logging.
Example:
options = Options()
options.log.level = "trace" # trace, debug, config, info, warn, error, fatalExample:
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"){ .api }
from selenium.webdriver.edge.options import Options as EdgeOptions
class Options(ChromiumOptions):
@property
def default_capabilities(self) -> dictDescription: 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"]){ .api }
from selenium.webdriver.safari.options import Options as SafariOptions
class Options(BaseOptions):
def __init__(self) -> NoneDescription: 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 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,
) -> NoneDescription: Base class for all service objects that launch driver processes.
Parameters:
executable_path: Path to the driver executableport: Port for the service to run on (0 = auto-assign)log_output: Logging output configurationenv: Environment variables for the processdriver_path_env_key: Environment variable for driver path{ .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,
) -> NoneExample:
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){ .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,
) -> NoneExample:
from selenium.webdriver.firefox.service import Service
service = Service(
executable_path="/path/to/geckodriver",
log_output="geckodriver.log",
service_args=["--log=trace"]
){ .api }
def start(self) -> NoneDescription: Starts the service.
Raises: WebDriverException if service cannot be started or connected to
{ .api }
def stop(self) -> NoneDescription: Stops the service.
{ .api }
def is_connectable(self) -> boolDescription: Check if the service is connectable.
Returns: True if service is accessible, False otherwise
{ .api }
@property
def service_url(self) -> strDescription: Gets the URL of the service.
Returns: Service URL (e.g., "http://localhost:4444")
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){ .api }
from selenium.webdriver.common.proxy import Proxy, ProxyType
class Proxy:
def __init__(self, raw: Optional[dict] = None) -> NoneDescription: Proxy configuration for WebDriver.
{ .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.
{ .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) -> NoneDescription: Manual proxy settings for different protocols.
{ .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) -> NoneDescription: SOCKS proxy authentication settings.
{ .api }
@property
def proxy_autoconfig_url(self) -> str
@proxy_autoconfig_url.setter
def proxy_autoconfig_url(self, value: str) -> NoneDescription: URL for proxy auto-configuration script.
{ .api }
@property
def auto_detect(self) -> bool
@auto_detect.setter
def auto_detect(self, value: bool) -> NoneDescription: Enable proxy auto-detection.
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 = 5PAC 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 = TrueNo 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.SYSTEMfrom 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
)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)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)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 driverThis 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