or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdapi-testing.mdassertions.mdbrowser-management.mdelement-location.mdindex.mdmobile-testing.mdnetwork-interception.mdpage-interaction.md
tile.json

tessl/pypi-playwright

A high-level API to automate web browsers across Chromium, Firefox and WebKit with both synchronous and asynchronous execution models.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/playwright@1.55.x

To install, run

npx @tessl/cli install tessl/pypi-playwright@1.55.0

index.mddocs/

Playwright

A comprehensive Python library for browser automation that provides a unified API for automating Chromium, Firefox, and WebKit browsers. Playwright enables reliable, fast, and ever-green automation with both synchronous and asynchronous execution models, supporting end-to-end testing, web scraping, and browser automation tasks with advanced features like auto-waiting, network interception, and mobile device emulation.

Package Information

  • Package Name: playwright
  • Language: Python
  • Installation: pip install playwright
  • Python Versions: 3.9+
  • Browser Setup: playwright install (downloads browser binaries)

Core Imports

Synchronous API (recommended for most use cases):

from playwright.sync_api import sync_playwright, Playwright, Browser, BrowserContext, Page, Locator, expect

Asynchronous API (for async/await patterns):

from playwright.async_api import async_playwright, Playwright, Browser, BrowserContext, Page, Locator, expect

Basic Usage

Synchronous Browser Automation

from playwright.sync_api import sync_playwright

# Launch browser and create page
with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    
    # Navigate and interact with page
    page.goto("https://example.com")
    page.click("text=More information")
    page.fill("#search-input", "automation")
    page.press("#search-input", "Enter")
    
    # Wait for and assert results
    page.wait_for_selector(".search-results")
    expect(page.locator(".search-results")).to_be_visible()
    
    # Take screenshot
    page.screenshot(path="results.png")
    browser.close()

Asynchronous Browser Automation

import asyncio
from playwright.async_api import async_playwright

async def run():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        
        await page.goto("https://example.com")
        await page.click("text=More information")
        await page.fill("#search-input", "automation")
        
        await browser.close()

asyncio.run(run())

Architecture

Playwright follows a hierarchical architecture that mirrors browser organization:

  • Playwright: Entry point providing access to browser types and global configuration
  • BrowserType: Represents browser engines (Chromium, Firefox, WebKit) with launch capabilities
  • Browser: Controls browser process, manages contexts and global settings
  • BrowserContext: Isolated session with independent state (cookies, storage, permissions)
  • Page: Individual browser tab with full automation capabilities
  • Frame: Document frame within a page (main frame or iframe)
  • Locator: Element finder with auto-waiting and retry logic
  • ElementHandle: Direct reference to DOM elements (lower-level API)

This design enables reliable automation by providing isolation between sessions, automatic waiting for elements, and consistent cross-browser behavior.

Capabilities

Browser Management

Launch and control browser instances across Chromium, Firefox, and WebKit. Supports both headless and headed modes, custom browser configurations, persistent contexts with user data, and connection to remote browser instances.

def sync_playwright() -> PlaywrightContextManager: ...
def async_playwright() -> PlaywrightContextManager: ...

class Playwright:
    chromium: BrowserType
    firefox: BrowserType  
    webkit: BrowserType
    devices: Dict[str, Dict]
    selectors: Selectors
    request: APIRequest

class BrowserType:
    def launch(**kwargs) -> Browser: ...
    def launch_persistent_context(user_data_dir: str, **kwargs) -> BrowserContext: ...
    def connect(ws_endpoint: str, **kwargs) -> Browser: ...

Browser Management

Page Interaction

Navigate web pages, interact with elements, and manipulate page content. Includes navigation methods, element interaction, form handling, JavaScript execution, and page state management with comprehensive waiting strategies.

class Page:
    def goto(url: str, **kwargs) -> Optional[Response]: ...
    def click(selector: str, **kwargs) -> None: ...
    def fill(selector: str, value: str, **kwargs) -> None: ...
    def type(selector: str, text: str, **kwargs) -> None: ...
    def wait_for_selector(selector: str, **kwargs) -> Optional[ElementHandle]: ...
    def screenshot(**kwargs) -> bytes: ...
    def evaluate(expression: str, arg: Any = None) -> Any: ...

Page Interaction

Element Location and Interaction

Modern element location using Locator API with built-in auto-waiting, retry logic, and robust element interaction methods. Supports various locator strategies including text content, ARIA roles, labels, and CSS selectors.

class Page:
    def locator(selector: str) -> Locator: ...
    def get_by_role(role: str, **kwargs) -> Locator: ...
    def get_by_text(text: str, **kwargs) -> Locator: ...
    def get_by_label(text: str, **kwargs) -> Locator: ...
    def get_by_test_id(test_id: str) -> Locator: ...

class Locator:
    def click(**kwargs) -> None: ...
    def fill(value: str, **kwargs) -> None: ...
    def is_visible(**kwargs) -> bool: ...
    def wait_for(**kwargs) -> None: ...
    def count() -> int: ...

Element Location

Network Interception

Intercept, modify, and mock network requests and responses. Enable testing of offline scenarios, API mocking, request/response modification, and comprehensive network monitoring for debugging and testing.

class Page:
    def route(url: Union[str, Pattern, Callable], handler: Callable) -> None: ...
    def unroute(url: Union[str, Pattern, Callable], handler: Optional[Callable] = None) -> None: ...

class BrowserContext:
    def route(url: Union[str, Pattern, Callable], handler: Callable) -> None: ...
    def set_extra_http_headers(headers: Dict[str, str]) -> None: ...

class Route:
    def abort(error_code: Optional[str] = None) -> None: ...
    def continue_(**kwargs) -> None: ...
    def fulfill(**kwargs) -> None: ...

Network Interception

Assertions and Testing

Comprehensive assertion framework with built-in waiting and retry logic for reliable test automation. Supports page, element, and API response assertions with detailed error reporting and configurable timeouts.

def expect(actual: Union[Page, Locator, APIResponse], message: Optional[str] = None) -> Union[PageAssertions, LocatorAssertions, APIResponseAssertions]: ...

class PageAssertions:
    def to_have_title(title: Union[str, Pattern], **kwargs) -> None: ...
    def to_have_url(url: Union[str, Pattern], **kwargs) -> None: ...

class LocatorAssertions:
    def to_be_visible(**kwargs) -> None: ...
    def to_have_text(expected: Union[str, Pattern, List], **kwargs) -> None: ...
    def to_have_count(count: int, **kwargs) -> None: ...
    def to_be_checked(**kwargs) -> None: ...

Assertions

API Testing

HTTP client for testing REST APIs and web services. Provides request/response handling, authentication, cookie management, and integration with browser contexts for end-to-end testing scenarios.

class APIRequest:
    def new_context(**kwargs) -> APIRequestContext: ...

class APIRequestContext:
    def get(url: str, **kwargs) -> APIResponse: ...
    def post(url: str, **kwargs) -> APIResponse: ...
    def put(url: str, **kwargs) -> APIResponse: ...
    def delete(url: str, **kwargs) -> APIResponse: ...

class APIResponse:
    def json() -> Any: ...
    def text() -> str: ...
    def status: int
    def ok: bool

API Testing

Mobile and Device Emulation

Emulate mobile devices, tablets, and various screen configurations. Includes pre-configured device profiles, custom viewport settings, touch interaction, geolocation, and user agent configuration for comprehensive mobile testing.

class BrowserContext:
    def set_geolocation(geolocation: Optional[Dict]) -> None: ...
    def grant_permissions(permissions: List[str], **kwargs) -> None: ...

class Page:
    @property
    def touchscreen() -> Touchscreen: ...

class Touchscreen:
    def tap(x: float, y: float) -> None: ...

Mobile Testing

Advanced Features

Specialized capabilities including WebSocket handling, video recording, accessibility testing, time manipulation, performance tracing, frame handling, and debugging tools for comprehensive browser automation testing.

class WebSocket:
    url: str
    def wait_for_event(event: str, **kwargs) -> Any: ...
    def is_closed() -> bool: ...

class Clock:
    def fast_forward(ticks: Union[int, str]) -> None: ...
    def install(time: Optional[Union[int, str, datetime.datetime]] = None) -> None: ...
    def pause_at(time: Union[int, str, datetime.datetime]) -> None: ...

class Video:
    def path() -> pathlib.Path: ...
    def save_as(path: Union[str, pathlib.Path]) -> None: ...

class Accessibility:
    def snapshot(root: Optional[ElementHandle] = None, **kwargs) -> Optional[Dict]: ...

Advanced Features

Data Structures

Core Types

# Geometry and positioning
class Position(TypedDict):
    x: float
    y: float

class FloatRect(TypedDict):
    x: float
    y: float
    width: float
    height: float

class ViewportSize(TypedDict):
    width: int
    height: int

# Browser configuration  
class Geolocation(TypedDict):
    latitude: float
    longitude: float
    accuracy: Optional[float]

class Cookie(TypedDict):
    name: str
    value: str
    domain: str
    path: str
    expires: Optional[float]
    httpOnly: Optional[bool]
    secure: Optional[bool]
    sameSite: Optional[str]

class HttpCredentials(TypedDict):
    username: str
    password: str

class ProxySettings(TypedDict):
    server: str
    bypass: Optional[str]
    username: Optional[str]
    password: Optional[str]

# Storage and session data
class StorageState(TypedDict):
    cookies: List[Cookie]
    origins: List[Dict]

class FilePayload(TypedDict):
    name: str
    mimeType: str
    buffer: bytes

# Network and request data
class ResourceTiming(TypedDict):
    startTime: float
    domainLookupStart: float
    domainLookupEnd: float
    connectStart: float
    connectEnd: float
    secureConnectionStart: float
    requestStart: float
    responseStart: float
    responseEnd: float

class RequestSizes(TypedDict):
    requestBodySize: int
    requestHeadersSize: int
    responseBodySize: int
    responseHeadersSize: int

class SourceLocation(TypedDict):
    url: str
    lineNumber: int
    columnNumber: int

class RemoteAddr(TypedDict):
    ipAddress: str
    port: int

class SecurityDetails(TypedDict):
    issuer: str
    protocol: str
    subjectName: str
    validFrom: float
    validTo: float

# PDF generation
class PdfMargins(TypedDict):
    top: Optional[str]
    bottom: Optional[str]
    left: Optional[str]
    right: Optional[str]

# Client certificates
class ClientCertificate(TypedDict):
    origin: str
    certPath: Optional[str]
    keyPath: Optional[str]
    passphrase: Optional[str]
    pfxPath: Optional[str]

Error Handling

class Error(Exception):
    """Base exception for all Playwright errors."""
    message: str
    name: str
    stack: str

class TimeoutError(Error):
    """Raised when operations exceed specified timeout."""
    pass

Common error patterns:

  • TimeoutError: Element not found, page load timeout, network timeout
  • Error: Element not actionable, navigation failed, context closed
  • Use try/except blocks around Playwright operations for robust error handling
  • Configure timeouts via timeout parameter in methods and global expect.set_options()