webdriver-management

A set of patterns for managing Selenium WebDriver, the tool that controls web browsers in automated tests. It covers creating browser drivers, waiting for pages, selecting browser options, cleaning up sessions, and running tests locally or remotely.

In plain words
What is it for?
Use it when building Selenium test infrastructure, supporting Chrome, Firefox, or Edge, configuring local or remote runs, and managing driver lifecycles.
Why use it?
It centralizes browser setup and cleanup, reducing duplicated configuration and unreliable tests caused by timing or unfinished browser sessions.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/tugkanboz/awesome-cursorrules/webdriver-management
Clone the repo
git clone --depth 1 https://github.com/tugkanboz/awesome-cursorrules

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 3,012 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.03012
Opus 5 $0.00000 $0.01506
Sonnet 5 $0.00000 $0.00602
Haiku 4.5 $0.00000 $0.00301

Measured yesterday against content hash da57161b69c9, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

webdriver-management scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

frameworks/selenium-python/.cursor/rules/patterns/webdriver-management.mdc · 424 lines

How it starts

The opening of the file, as written. The whole thing — 424 lines — stays where its author put it; the contents beside it link to each section on GitHub.

WebDriver Management Excellence

Modern WebDriver Architecture

  • Factory Pattern: Centralized driver creation with configuration
  • Session Management: Proper lifecycle and resource cleanup
  • Cross-Browser Support: Unified interface for different browsers
  • Grid Integration: Seamless local and remote execution

Advanced Driver Factory

from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
from typing import Dict, Any, Optional
import os
import logging

logger = logging.getLogger(__name__)

class WebDriverFactory:
    """Advanced WebDriver factory with comprehensive configuration."""
    
    SUPPORTED_BROWSERS = ['chrome', 'firefox', 'edge']
    
    def __init__(self, config: Dict[str, Any]):
        self.config = config
        self.drivers = []  # Track created drivers for cleanup
    
    def create_driver(self, browser: str, headless: bool = False, 
                     remote_url: Optional[str] = None) -> webdriver.Remote:
        """Create WebDriver instance with advanced configuration."""
        
        if browser.lower() not in self.SUPPORTED_BROWSERS:
            raise ValueError(f"Unsupported browser: {browser}. Supported: {self.SUPPORTED_BROWSERS}")
        
        try:
            if remote_url:
                driver = self._create_remote_driver(browser, headless, remote_url)
            else:
                driver = self._create_local_driver(browser, headless)
            
            # Configure driver settings
            self._configure_driver(driver)
            self.drivers.append(driver)
            
            logger.info(f"Created {browser} driver (headless: {headless}, remote: {bool(remote_url)})")
            return driver
            
        except Exception as e:
            logger.error(f"Failed to create {browser} driver: {str(e)}")
            raise
    
    def _create_local_driver(self, browser: str, headless: bool) -> webdriver.Remote:
        """Create local WebDriver instance."""
        browser = browser.lower()
        
        if browser == 'chrome':
            return self._create_chrome_driver(headless)
        elif browser == 'firefox':
            return self._create_firefox_driver(headless)
        elif browser == 'edge':
            return self._create_edge_driver(headless)
        else:
            raise ValueError(f"Unsupported browser: {browser}")
    
    def _create_remote_driver(self, browser: str, headless: bool, remote_url: str) -> webdriver.Remote:
        """Create remote WebDriver instance for Selenium Grid."""
        capabilities = self._get_capabilities(browser, headless)
        
        driver = webdriver.Remote(
            command_executor=remote_url,
            desired_capabilities=capabilities
        )
        
        return driver
    
    def _create_chrome_driver(self, headless: bool) -> webdriver.Chrome:
        """Create optimized Chrome driver."""
        options = ChromeOptions()
        
        # Performance optimizations
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--disable-gpu")
        options.add_argument("--disable-web-security")
        options.add_argument("--allow-running-insecure-content")
        options.add_argument("--disable-extensions")
        options.add_argument("--disable-plugins")
        options.add_argument("--disable-images")
        
        # Window configuration
        options.add_argument("--window-size=1920,1080")
        options.add_argument("--start-maximized")
        
        if headless:
            options.add_argument("--headless=new")  # Use new headless mode
        
        # Additional options from config
        if 'chrome_options' in self.config:
            for option in self.config['chrome_options']:
                options.add_argument(option)
        
        # Preferences
        prefs = {
            "profile.default_content_setting_values": {
                "notifications": 2,  # Block notifications
                "geolocation": 2,    # Block location sharing
            },
            "profile.managed_default_content_settings": {
                "images": 2  # Block images for faster loading
            }
        }
        options.add_experimental_option("prefs", prefs)
        
        # Service configuration
        service = ChromeService(ChromeDriverManager().install())
        
        return webdriver.Chrome(service=service, options=options)
    
    def _create_firefox_driver(self, headless: bool) -> webdriver.Firefox:
        """Create optimized Firefox driver."""
        options = FirefoxOptions()
        
        # Performance optimizations
        options.set_preference("dom.webnotifications.enabled", False)
        options.set_preference("media.volume_scale", "0.0")
        options.set_preference("browser.cache.disk.enable", False)
        options.set_preference("browser.cache.memory.enable", False)
        options.set_preference("network.http.use-cache", False)
        
        if headless:
            options.add_argument("--headless")
        
        # Window size
        options.add_argument("--width=1920")
        options.add_argument("--height=1080")
        
        service = FirefoxService(GeckoDriverManager().install())
        
        return webdriver.Firefox(service=service, options=options)
    
    def _create_edge_driver(self, headless: bool) -> webdriver.Edge:
        """Create optimized Edge driver."""
        options = EdgeOptions()
        
        # Similar optimizations as Chrome
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--disable-gpu")
        options.add_argument("--window-size=1920,1080")
        
        if headless:
            options.add_argument("--headless")
        
        service = EdgeService(EdgeChromiumDriverManager().install())
        
        return webdriver.Edge(service=service, options=options)
    
    def _get_capabilities(self, browser: str, headless: bool) -> Dict[str, Any]:
        """Get capabilities for remote WebDriver."""
        capabilities = {
            'chrome': {
                "browserName": "chrome",
                "version": "latest",
                "platform": "ANY",
                "chromeOptions": {
                    "args": ["--no-sandbox", "--disable-dev-shm-usage"]
                }
            },
            'firefox': {
                "browserName": "firefox",
                "version": "latest",
                "platform": "ANY"
            },
            'edge': {
                "browserName": "MicrosoftEdge",
                "version": "latest",
                "platform": "ANY"
            }
        }
        
        caps = capabilities.get(browser.lower(), capabilities['chrome'])
        
        if headless:
            if browser.lower() == 'chrome':
                caps["chromeOptions"]["args"].append("--headless=new")
            elif browser.lower() == 'firefox':
                caps["moz:firefoxOptions"] = {"args": ["--headless"]}
        
        return caps
    
    def _configure_driver(self, driver: webdriver.Remote) -> None:
        """Configure driver with common settings."""
        # Timeouts
        driver.implicitly_wait(self.config.get('implicit_wait', 10))
        driver.set_page_load_timeout(self.config.get('page_load_timeout', 30))
        driver.set_script_timeout(self.config.get('script_timeout', 30))
        
        # Window management
        try:
            driver.maximize_window()
        except Exception:
            # Some drivers/environments don't support maximize
            driver.set_window_size(1920, 1080)
    
    def quit_all_drivers(self) -> None:
        """Clean up all created drivers."""
        for driver in self.drivers:
            try:
                driver.quit()
                logger.debug("Driver cleanup successful")
            except Exception as e:
                logger.warning(f"Driver cleanup failed: {str(e)}")
        
        self.drivers.clear()

Read the full file on GitHub · 424 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 424 lines · 3,012 tokens per session scan A da57161b69c9

Subscribe to this mod's changes

webdriver-management is a cursor rule published in the GitHub repository tugkanboz/awesome-cursorrules (20 stars, last pushed 2d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 3,012 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.