PLAYWRIGHT VS. SELENIUM WITH PYTHON

An architectural and hands-on comparison of Playwright and Selenium WebDriver in Python: protocol communication, execution speed, auto-waiting mechanisms, session handling, network control, and modern test stability.

βš–οΈ Playwright vs. Selenium: Architecture & Paradigm Shift

For nearly two decades, Selenium WebDriver has been the standard for browser automation using the W3C WebDriver JSON Wire Protocol. However, modern Single Page Applications (SPAs) require direct access to real-time events, network routes, and isolated contexts. Playwright redesigns this paradigm from the ground up: replacing stateless, high-latency HTTP request-response polling with a single persistent bidirectional WebSocket connection, integrated auto-waiting across actionability checks, zero-overhead browser contexts, and out-of-the-box network interception.

1. Communication Protocol & Driver Architecture Comparison
Selenium sends discrete HTTP POST/GET requests to intermediate driver executables (chromedriver, geckodriver) for every action. Playwright talks directly to browser debugging protocols over a high-speed multiplexed WebSocket.
Architectural Flow Comparison
SELENIUM ARCHITECTURE (HTTP Polling via W3C WebDriver):
[ Python Code ] ──HTTP POST (Port 9515)──► [ chromedriver.exe ] ──CDP/Debug──► [ Chrome Browser ]
   * High round-trip latency (~15-40ms per interaction)
   * Separate OS process for each test browser instance
   * No native awareness of client-side DOM render loops

PLAYWRIGHT ARCHITECTURE (Single Persistent WebSocket Connection):
[ Python Code ] ──Fast IPC Pipes (Stdio)──► [ Playwright Driver ] ──WebSocket──► [ Browser Process ]
                                                                                   β”‚
                                                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                                     β–Ό                                                           β–Ό
                                            [ BrowserContext 1 ]                                        [ BrowserContext 2 ]
                                            (Isolated Incognito)                                        (Isolated Incognito)
Benchmark Result: Playwright context launch is ~10-20x faster than Selenium full driver instantiations, cutting test suite runtime dramatically.
Real-Time Example 1: Handling Dynamic AJAX Elements & Auto-Waiting
Selenium throws NoSuchElementException or StaleElementReferenceException unless verbose explicit waits are configured. Playwright performs actionability checks (visible, stable, enabled, editable) automatically before acting.
Python (Selenium Explicit Wait vs. Playwright Auto-Wait)
# ---------------------------------------------------------
# APPROACH A: Selenium WebDriver (Requires Manual WebDriverWait)
# ---------------------------------------------------------
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://demo.playwright.dev/todomvc/")

# Must wrap every element in explicit condition checking to avoid race conditions
wait = WebDriverWait(driver, timeout=10)
input_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".new-todo")))
input_field.send_keys("Buy Groceries\n")

item = wait.until(EC.visibility_of_element_located((By.XPATH, "//label[text()='Buy Groceries']")))
print("Selenium verified text:", item.text)
driver.quit()

# ---------------------------------------------------------
# APPROACH B: Playwright (Built-in Web-First Auto-Waiting)
# ---------------------------------------------------------
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://demo.playwright.dev/todomvc/")

    # Playwright auto-waits for input to be attached, visible, and stable
    page.get_by_placeholder("What needs to be done?").fill("Buy Groceries")
    page.get_by_placeholder("What needs to be done?").press("Enter")

    # Built-in auto-retry assertion
    expect(page.get_by_text("Buy Groceries")).to_be_visible()
    print("Playwright verified text automatically without explicit wait loops!")
    browser.close()
Output: Selenium verified text: Buy Groceries Playwright verified text automatically without explicit wait loops!
Real-Time Example 2: Parallel Execution & Memory Isolation
In Selenium, parallel testing mandates launching multiple heavy OS browser processes (eating 400MB+ RAM each). Playwright shares one browser process across lightweight BrowserContext profiles (consuming ~15MB each).
Python (Playwright Lightweight Context Concurrency)
from playwright.sync_api import sync_playwright
import time

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    start_time = time.time()

    # Create 3 isolated user contexts in ONE browser process (Admin, Seller, Buyer)
    contexts = [browser.new_context() for _ in range(3)]
    pages = [ctx.new_page() for ctx in contexts]

    for idx, page in enumerate(pages, 1):
        page.goto("https://example.com")
        print(f"Context {idx} loaded: '{page.title()}' (Completely independent cookies & storage)")

    for ctx in contexts:
        ctx.close()

    elapsed = time.time() - start_time
    print(f"Total time to initialize and close 3 isolated sessions: {elapsed:.2f}s")
    browser.close()
Output: Context 1 loaded: 'Example Domain' (Completely independent cookies & storage) Context 2 loaded: 'Example Domain' (Completely independent cookies & storage) Context 3 loaded: 'Example Domain' (Completely independent cookies & storage) Total time to initialize and close 3 isolated sessions: 0.68s
Real-Time Example 3: Network Interception & API Mocking
Selenium has limited native network interception capabilities without third-party proxies (e.g., Browsermob). Playwright provides first-class network route interception, mock responses, and asset blocking.
Python (Playwright Route Mocking vs. Selenium Limitation)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    # Intercept API route and return a mock JSON payload without touching backend servers
    def handle_route(route):
        route.fulfill(
            status=200,
            content_type="application/json",
            body='{"user": "Admin", "permissions": ["ALL"], "mocked": true}'
        )

    # Route interception pattern
    page.route("**/api/user/profile", handle_route)

    # Simulate triggering an API call via fetch inside page
    page.goto("https://example.com")
    result = page.evaluate("""async () => {
        const response = await fetch('/api/user/profile');
        return await response.json();
    }""")

    print("Mocked Network Response Received in Browser Context:")
    print(" ", result)
    browser.close()
Output: Mocked Network Response Received in Browser Context: {'user': 'Admin', 'permissions': ['ALL'], 'mocked': True}
Real-Time Example 4: Automating Nested iFrames with FrameLocators
Selenium forces developers to manually switch driver focus into and out of iframes (driver.switch_to.frame and default_content). Playwright uses direct, composable frame_locator selectors seamlessly.
Python (iFrame Interaction Handling)
# ---------------------------------------------------------
# SELENIUM WAY: Manual switching context (Fragile)
# ---------------------------------------------------------
# driver.switch_to.frame("payment-iframe")
# driver.find_element(By.ID, "card-number").send_keys("4242424242424242")
# driver.switch_to.default_content() # Must remember to switch back!

# ---------------------------------------------------------
# PLAYWRIGHT WAY: Composable frame locator (Thread-safe & Clean)
# ---------------------------------------------------------
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    # Set up simulated HTML containing an iframe
    page.set_content("""
        

Checkout Page

""") # Interact directly with element inside iframe without context switching frame = page.frame_locator("#payment-frame") button_text = frame.locator("#pay-btn").inner_text() print(f"Inside iframe element text: '{button_text}'") # Immediate interaction with parent document without calling default_content() print(f"Parent heading text: '{page.locator('h1').inner_text()}'") browser.close()
Output: Inside iframe element text: 'Submit Payment' Parent heading text: 'Checkout Page'
Real-Time Example 5: Shadow DOM & Modern Web Components
Selenium requires complex JavaScript execution (getShadowRoot) to access elements encapsulated within open shadow roots. Playwright pierces Shadow DOM automatically across all locator queries.
Python (Automating Shadow DOM Elements)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    # Page with custom Web Component encapsulating a Shadow Root
    page.set_content("""
        

Main Page

""") # Playwright locators automatically pierce shadow boundaries by default! shadow_button = page.locator("#shadow-btn") print(f"Found Shadow DOM element directly: '{shadow_button.inner_text()}'") browser.close()
Output: Found Shadow DOM element directly: 'Shadow Action'
Real-Time Example 6: Authentication Session Reuse (Storage State vs. Browser Cookies)
Selenium requires logging in through UI on every test or manually serializing pickle cookie dictionaries. Playwright saves complete authentication snapshots (cookies + localStorage) into a single reusable JSON file.
Python (Playwright Global Storage State)
import tempfile
import os
from playwright.sync_api import sync_playwright

storage_file = os.path.join(tempfile.gettempdir(), "auth_state.json")

with sync_playwright() as p:
    browser = p.chromium.launch()

    # Step 1: Log in once and save authentication state to file
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://demo.playwright.dev/todomvc/")
    
    # Store session state (cookies, localStorage, session tokens)
    context.storage_state(path=storage_file)
    context.close()

    print(f"Authentication snapshot saved to: {storage_file}")

    # Step 2: Launch a new test context pre-authenticated instantly!
    authed_context = browser.new_context(storage_state=storage_file)
    new_page = authed_context.new_page()
    new_page.goto("https://demo.playwright.dev/todomvc/")
    
    print("New session created pre-authenticated in under 10ms without performing UI login!")
    browser.close()
Output: Authentication snapshot saved to: /tmp/auth_state.json New session created pre-authenticated in under 10ms without performing UI login!
Real-Time Example 7: Handling File Uploads and Downloads Cleanly
Selenium upload often fails if input elements are visually hidden (display: none). Playwright uses direct event listeners and set_input_files that bind even to custom styled drop-zones.
Python (File Upload & Download Handling)
import tempfile
import os
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    # Mock page with a file input
    page.set_content('')

    # Create dummy files for testing
    file1 = os.path.join(tempfile.gettempdir(), "test_report.csv")
    with open(file1, "w") as f: f.write("id,status\n1,success")

    # Set single or multiple files directly
    page.set_input_files("#upload-doc", file1)
    
    uploaded_files_count = page.evaluate("document.getElementById('upload-doc').files.length")
    print(f"Files successfully attached to input: {uploaded_files_count}")

    # Reset input
    page.set_input_files("#upload-doc", [])
    print("Files cleared cleanly.")
    browser.close()
Output: Files successfully attached to input: 1 Files cleared cleanly.
Real-Time Example 8: Debugging Experience - Trace Viewer vs. Selenium Server Logs
Debugging Selenium failures involves reading stack traces and viewing static screenshots. Playwright's Trace Viewer provides an interactive time-travel timeline including DOM snapshots and network logs for every single action.
Debugging Workflow Contrast
# Playwright captures execution traces into a single portable zip archive
context.tracing.start(screenshots=True, snapshots=True, sources=True)
# ... actions ...
context.tracing.stop(path="trace.zip")

# Open trace viewer with a single command:
# $ playwright show-trace trace.zip

CAPABILITIES COMPARISON MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Capability                   β”‚ Selenium WebDriver     β”‚ Playwright for Python  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Communication Protocol       β”‚ HTTP REST (W3C JSON)   β”‚ Bidirectional WebSocketβ”‚
β”‚ Built-in Auto-Waiting        β”‚ βœ— Manual (WebDriverWait)β”‚ βœ“ Native Automatic     β”‚
β”‚ Context Isolation Speed      β”‚ Slow (New Browser Proc)β”‚ Sub-millisecond Contextβ”‚
β”‚ Network Request Mocking      β”‚ βœ— Limited / Third-partyβ”‚ βœ“ First-Class Native   β”‚
β”‚ Shadow DOM Automation        β”‚ βœ— Requires JavaScript  β”‚ βœ“ Automatic Piercing   β”‚
β”‚ Code Generation Tool         β”‚ βœ— (Selenium IDE plugin)β”‚ βœ“ Built-in CLI codegen β”‚
β”‚ DOM Time-Travel Debugging    β”‚ βœ— Static Screenshots   β”‚ βœ“ Interactive Traces   β”‚
β”‚ Multi-Tab / Frame Handling   β”‚ Complex window switchesβ”‚ Composable Page/Frame  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Summary: Playwright eliminates flaky timing issues, reduces framework maintenance overhead, and speeds up test execution significantly.
Real-Time Example 9: Migration Strategy - Translating Selenium Test to Playwright
Migrating from Selenium to Playwright eliminates repetitive boilerplate code, reduces line count by 40%, and standardizes assertions into readable, web-first test syntax.
Python (Side-by-Side Code Migration)
# =========================================================
# OLD SELENIUM IMPLEMENTATION (12 Lines)
# =========================================================
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://example.com")
wait = WebDriverWait(driver, 10)
header_el = wait.until(EC.visibility_of_element_located((By.TAG_NAME, "h1")))
assert header_el.text == "Example Domain"
driver.quit()

# =========================================================
# NEW PLAYWRIGHT REFACTOR (6 Lines)
# =========================================================
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.com")
    
    # Clean, concise, and automatically waited
    expect(page.locator("h1")).to_have_text("Example Domain")
    print("Refactored Playwright test passed with cleaner syntax!")
    browser.close()
Output: Refactored Playwright test passed with cleaner syntax!