Selenium Cheatsheet

Setup

Use this Selenium reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Installation

Selenium scripts drive a real browser, so setup is different from a generic online compiler. Use Hack University's Python online compiler to practice helper functions or parsing code, then run Selenium tests locally or in CI where Chrome, Firefox, or Edge drivers are available.

pip install selenium

Since Selenium 4.6, Selenium Manager ships inside the selenium package and automatically downloads and caches the matching driver (and even a browser binary if none is installed) — no manual driver setup and no webdriver-manager needed.

Manual driver downloads (only for air-gapped/pinned environments): - Chrome: Chrome for Testing (chromedriver.chromium.org is deprecated and only covers Chrome ≤115) - Firefox: github.com/mozilla/geckodriver - Edge: developer.microsoft.com/en-us/microsoft-edge/tools/webdriver

Driver Initialization

Selenium Manager resolves the driver automatically — plain construction is the canonical pattern for every browser:

from selenium import webdriver

driver = webdriver.Chrome()    # driver resolved by Selenium Manager
driver = webdriver.Firefox()
driver = webdriver.Edge()

With Options

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

options = Options()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)

Pinned Driver Binary (explicit Service)

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

service = Service(executable_path="/path/to/chromedriver")
driver = webdriver.Chrome(service=service)

Safari

from selenium import webdriver

# SafariDriver ships with macOS; enable via: safaridriver --enable
driver = webdriver.Safari()

Legacy: webdriver-manager (ChromeDriverManager().install()) predates Selenium Manager and is unnecessary on Selenium ≥4.6 — remove it when upgrading old suites.

Common Chrome Options

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless=new")          # headless mode (Selenium 4+)
options.add_argument("--no-sandbox")            # required in some CI environments
options.add_argument("--disable-dev-shm-usage") # overcome limited /dev/shm in Docker
options.add_argument("--disable-gpu")           # needed in headless on some systems
options.add_argument("--window-size=1920,1080")
options.add_argument("--disable-extensions")
options.add_argument("--incognito")
options.add_argument("--ignore-certificate-errors")
options.add_argument("--user-agent=Mozilla/5.0 ...")

# Binary location override
options.binary_location = "/path/to/chrome"

# Disable infobars / automation banner
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)

# Set download directory
prefs = {"download.default_directory": "/tmp/downloads"}
options.add_experimental_option("prefs", prefs)

Common Firefox Options

from selenium.webdriver.firefox.options import Options

options = Options()
options.add_argument("--headless")
options.add_argument("--width=1920")
options.add_argument("--height=1080")

# Firefox profile preferences
options.set_preference("browser.download.dir", "/tmp/downloads")
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")

Remote / Selenium Grid

from selenium import webdriver

# Selenium Grid 4 (W3C protocol — configure via Options, not DesiredCapabilities)
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Remote(
    command_executor="http://localhost:4444",   # Grid 4; legacy hubs use /wd/hub
    options=options
)

CDP and BiDi (Selenium 4)

Chrome DevTools Protocol — execute_cdp_cmd (Chromium only)

# Works on Chrome/Edge local drivers
driver.execute_cdp_cmd("Network.enable", {})
driver.execute_cdp_cmd("Network.setBlockedURLs", {"urls": ["*doubleclick.net*"]})
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", {
    "latitude": 37.7749, "longitude": -122.4194, "accuracy": 100
})
driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {
    "headers": {"X-Test-Run": "42"}
})

WebDriver BiDi (cross-browser: Chrome, Edge, Firefox)

from selenium import webdriver

options = webdriver.ChromeOptions()
options.enable_bidi = True                       # opens the BiDi websocket
driver = webdriver.Chrome(options=options)

# Capture browser console messages
driver.script.add_console_message_handler(lambda entry: print(entry.text))

# Intercept / mutate network requests (glob URL patterns)
def block_analytics(request):
    request.fail()
driver.network.add_request_handler(["**/analytics/**"], block_analytics)

# Auto-answer HTTP Basic/Digest auth challenges
driver.network.add_auth_handler("user", "s3cret")

driver.get("https://example.com")

Prefer BiDi for new code — it is the W3C standard and works across browsers; execute_cdp_cmd is Chromium-specific and tied to the browser's CDP version.

Teardown

driver.close()   # close current tab only
driver.quit()    # close all tabs and end the session (always prefer this)

Always call driver.quit() in a finally block or use a context manager to avoid leaving browser processes running.

Context Manager Pattern

from contextlib import contextmanager
from selenium import webdriver

@contextmanager
def get_driver():
    driver = webdriver.Chrome()
    try:
        yield driver
    finally:
        driver.quit()

with get_driver() as driver:
    driver.get("https://example.com")

Selenium Version Check

import selenium
print(selenium.__version__)   # e.g. "4.x.x"

Selenium 4+ uses W3C WebDriver protocol exclusively. DesiredCapabilities is deprecated — use browser-specific Options objects instead.