ZetCode

Python Playwright

last modified November 17, 2026 Python 3.15

In this article we show how to automate web browsers in Python with Playwright.

Playwright is a browser automation library developed by Microsoft. It drives the three major rendering engines: Chromium (Google Chrome, Microsoft Edge), Firefox (Gecko), and WebKit (Safari) through a single API. Playwright is available for Node.js, Python, Java, and .NET; the Python package is called playwright.

Playwright is used for end-to-end testing of web applications, for scraping pages that are rendered by JavaScript, for taking screenshots and generating PDFs, and for automating repetitive tasks in the browser. Unlike plain HTTP clients such as requests or httpx, Playwright runs a real browser, so the JavaScript on the page is executed and we work with the same DOM a user sees.

The Python library has two flavours of the same API: a synchronous one in playwright.sync_api and an asynchronous one in playwright.async_api. By default, browsers run in headless mode, which means that no window is shown.

The examples in this article were tested with Python 3.15, Playwright 1.65, and pytest-playwright 0.10 on Linux.

Installation

Playwright is installed in two steps. First we install the Python package with pip, then we download the browsers with the playwright install command. Each Playwright release is tied to specific browser builds, so the second step must be repeated after upgrading the package.

The playwright install command without arguments downloads Chromium, Firefox, and WebKit; we can also install only the browsers we need. On Linux, the --with-deps option additionally installs the system libraries the browsers depend on (it uses the system package manager and needs root privileges). The browsers are stored in ~/.cache/ms-playwright on Linux; the location can be changed with the PLAYWRIGHT_BROWSERS_PATH environment variable.

$ python -m venv .venv
$ source .venv/bin/activate
$ pip install playwright
$ playwright install chromium firefox webkit

Getting the page title

In the first example, we open a web page and print its title.

title.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    page.goto('https://example.com')

    print(page.title())
    print(page.url)

    browser.close()

The program launches Chromium, navigates to example.com, and prints the title and the URL of the page.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:

The sync_playwright function starts the Playwright driver, a separate process that controls the browsers. Using it as a context manager guarantees that the driver is stopped when the block ends. The returned object gives access to the browser types: p.chromium, p.firefox, and p.webkit.

browser = p.chromium.launch()
page = browser.new_page()

The launch method starts a headless Chromium. The new_page method opens a new tab in a fresh browser context. A browser context is an isolated, incognito-like session with its own cookies and storage; it is described later.

page.goto('https://example.com')

The goto method navigates to the URL and waits until the page fires the load event. It returns the response of the main document.

print(page.title())
print(page.url)

We print the content of the title element and the final URL of the page. Note that the browser added a trailing slash to the URL.

browser.close()

We close the browser and all its pages.

$ python title.py
Example Domain
https://example.com/

The demo site

To keep the examples reproducible, most of them work with a small local website. The site consists of a home page, a page that loads a list of books with JavaScript, and an order form. The files are stored in the site subdirectory.

site/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bookshop</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<h1>Bookshop</h1>

<nav>
    <a href="books.html">Books</a>
    <a href="order.html">Order</a>
</nav>

<h2>Popular topics</h2>

<ul class="topics">
    <li>Python</li>
    <li>JavaScript</li>
    <li>Rust</li>
    <li>Go</li>
    <li>Databases</li>
</ul>

<p data-testid="note">New titles arrive every Monday.</p>

</body>
</html>

The home page contains a heading, two navigation links, a list of topics, and a paragraph with a data-testid attribute.

site/style.css
body { font-family: sans-serif; margin: 2em; max-width: 40em; }
nav a { margin-right: 1em; }
table { border-collapse: collapse; }
th, td { border: 1px solid #999; padding: 0.3em 0.6em; text-align: left; }
form { display: grid; grid-template-columns: max-content 14em; gap: 0.5em 1em; }
form button { grid-column: 2; justify-self: start; }

The style sheet is shared by all pages of the site.

We serve the directory with the HTTP server from the standard library. The server must keep running in a separate terminal while we execute the examples.

$ python -m http.server 8000 -d site
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

Chromium, Firefox, and WebKit

The same code can drive all three browser engines.

browsers.py
from playwright.sync_api import sync_playwright

url = 'http://localhost:8000/'

with sync_playwright() as p:

    for browser_type in (p.chromium, p.firefox, p.webkit):

        browser = browser_type.launch()
        page = browser.new_page()
        page.goto(url)

        print(f'{browser_type.name:<9} {browser.version:<14} {page.title()}')

        browser.close()

We loop over the three browser types, launch each browser, and print its name, version, and the title of the home page of our demo site.

for browser_type in (p.chromium, p.firefox, p.webkit):

The chromium, firefox, and webkit attributes are BrowserType objects. Their name attribute holds the name of the engine; the version attribute of a launched browser holds the browser version.

Playwright uses patched builds of Firefox and WebKit, so the WebKit engine can be tested on Linux and Windows too, not only on macOS. To run tests in an installed branded browser, pass the channel option, for instance p.chromium.launch(channel='chrome') or channel='msedge'.

$ python browsers.py
chromium  159.0.8154.6   Bookshop
firefox   159.0          Bookshop
webkit    27.2           Bookshop

Screenshots

The screenshot method captures the page or a single element as a PNG or JPEG image.

screenshot.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page(viewport={'width': 640, 'height': 240})

    page.goto('http://localhost:8000/')

    page.screenshot(path='viewport.png')
    page.screenshot(path='full.png', full_page=True)
    page.locator('ul.topics').screenshot(path='topics.png')

    browser.close()

The program creates three screenshots of the home page.

page = browser.new_page(viewport={'width': 640, 'height': 240})

The default viewport is 1280x720 pixels. We set a small viewport so that the page does not fit into it.

page.screenshot(path='viewport.png')
page.screenshot(path='full.png', full_page=True)

The first screenshot contains only the visible part of the page. With full_page=True, Playwright captures the whole scrollable page. The image format is determined from the file extension; the type and quality options control it explicitly. Without the path option, the method returns the image as bytes.

page.locator('ul.topics').screenshot(path='topics.png')

Calling screenshot on a locator captures only the matching element. Locators are covered in a later section.

Full-page screenshot of the demo site
Figure: Full-page screenshot

The file command shows that the full-page screenshot is taller than the viewport.

$ python screenshot.py
$ file *.png
full.png:     PNG image data, 640 x 332, 8-bit/color RGB, non-interlaced
topics.png:   PNG image data, 576 x 91, 8-bit/color RGB, non-interlaced
viewport.png: PNG image data, 640 x 240, 8-bit/color RGB, non-interlaced

Generating PDF

The pdf method prints the page to a PDF file. It is supported only in Chromium.

pdf.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    page.goto('http://localhost:8000/')
    page.pdf(path='bookshop.pdf', format='A4', print_background=True,
             margin={'top': '2cm', 'bottom': '2cm'})

    browser.close()

The example saves the home page as an A4 PDF document.

page.pdf(path='bookshop.pdf', format='A4', print_background=True,
         margin={'top': '2cm', 'bottom': '2cm'})

The format option sets the paper size and margin the page margins. Browsers omit background colours and images when printing; print_background=True keeps them. The PDF is created with the print CSS media type; we can call page.emulate_media(media='screen') before to get the screen styles instead.

$ python pdf.py
$ pdfinfo bookshop.pdf | grep -E "Producer|Pages|Page size"
Producer:        Skia/PDF m159
Pages:           1
Page size:       595.92 x 842.88 pts (A4)

Locators

A locator describes how to find elements on the page. Creating a locator does not search the page; the elements are looked up each time an action or a query is performed. Thanks to this, a locator always works with the current state of the page, even if the DOM has been re-rendered.

Playwright recommends locating elements the way users perceive them: by their ARIA role and accessible name (get_by_role), by text (get_by_text), by the label of a form control (get_by_label), by placeholder (get_by_placeholder), or by a dedicated test id (get_by_test_id). CSS and XPath selectors are available through the generic locator method.

locators.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('http://localhost:8000/')

    heading = page.get_by_role('heading', level=1)
    print(heading.text_content())

    topics = page.locator('ul.topics li')
    print(topics.count())
    print(topics.all_text_contents())
    print(topics.first.text_content(), topics.last.text_content())
    print(topics.nth(2).text_content())

    print(topics.filter(has_text='Script').text_content())

    link = page.get_by_role('link', name='Books')
    print(link.get_attribute('href'))

    print(page.get_by_test_id('note').inner_text())

    for item in topics.all():
        print(item.inner_text().lower())

    browser.close()

The program locates various elements on the home page of our site.

heading = page.get_by_role('heading', level=1)
print(heading.text_content())

We find the h1 element by its role and level.

topics = page.locator('ul.topics li')
print(topics.count())
print(topics.all_text_contents())

A CSS selector finds all items of the topics list. The count method returns the number of matching elements and all_text_contents their text contents as a list.

print(topics.first.text_content(), topics.last.text_content())
print(topics.nth(2).text_content())

The first, last, and nth properties narrow a locator to a single element; nth is zero-based.

print(topics.filter(has_text='Script').text_content())

The filter method narrows the locator to elements that contain the given text. Calling text_content on a locator that matches more than one element would raise an error; Playwright operates in strict mode and refuses to guess which element we mean.

link = page.get_by_role('link', name='Books')
print(link.get_attribute('href'))

We find the link by its accessible name and read its href attribute.

print(page.get_by_test_id('note').inner_text())

The get_by_test_id method looks for the data-testid attribute. The difference between inner_text and text_content is that the former returns the rendered text, as it appears on the screen, while the latter returns the raw text of the DOM node, including the text of hidden elements.

for item in topics.all():
    print(item.inner_text().lower())

The all method returns a list of locators, one for each matching element, so that we can work with the elements one by one.

$ python locators.py
Bookshop
5
['Python', 'JavaScript', 'Rust', 'Go', 'Databases']
Python Databases
Rust
JavaScript
books.html
New titles arrive every Monday.
python
javascript
rust
go
databases

Clicking and auto-waiting

Modern pages load data in the background and update the DOM later. In the following example, we click on a button that loads a list of books. The page delays the request on purpose to simulate a slow network.

site/books.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Books</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<h1>Books</h1>

<button id="load">Load books</button>
<p id="status" role="status"></p>

<table id="books">
    <thead>
    <tr><th>Title</th><th>Author</th><th>Price</th></tr>
    </thead>
    <tbody></tbody>
</table>

<script>
const button = document.getElementById('load');
const status = document.getElementById('status');
const tbody = document.querySelector('#books tbody');

button.addEventListener('click', async () => {
    status.textContent = 'Loading...';
    await new Promise(resolve => setTimeout(resolve, 1500));

    const resp = await fetch('books.json');
    const books = await resp.json();

    for (const book of books) {
        const row = tbody.insertRow();
        row.insertCell().textContent = book.title;
        row.insertCell().textContent = book.author;
        row.insertCell().textContent = book.price.toFixed(2);
    }

    status.textContent = `Loaded ${books.length} books`;
    console.log(`rendered ${books.length} rows`);
});
</script>

</body>
</html>

After the button is clicked, the script shows a Loading... message, waits for 1.5 seconds, fetches books.json, fills the table, and updates the status message. It also writes a message to the browser console.

site/books.json
[
    {"title": "Fluent Python", "author": "Luciano Ramalho", "price": 59.99},
    {"title": "Python Crash Course", "author": "Eric Matthes", "price": 39.99},
    {"title": "Effective Python", "author": "Brett Slatkin", "price": 44.99},
    {"title": "Python Tricks", "author": "Dan Bader", "price": 29.99}
]

The JSON file contains the data for the table.

load_books.py
import time

from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('http://localhost:8000/books.html')

    start = time.perf_counter()

    page.get_by_role('button', name='Load books').click()

    status = page.get_by_role('status')
    print(status.text_content())

    expect(status).to_have_text('Loaded 4 books')
    print(status.text_content())

    print(f'waited {time.perf_counter() - start:.1f} s')

    browser.close()

The program clicks the button and waits until the status message shows that the books were loaded.

page.get_by_role('button', name='Load books').click()

Before Playwright performs an action, it waits until the element is attached to the DOM, visible, stable (not animated), enabled, and receives pointer events. This is called auto-waiting; we do not need to put time.sleep calls into the code. If the element is not ready within 30 seconds, the action fails with a TimeoutError. The timeout can be changed for a single call with the timeout option or for the whole page with page.set_default_timeout.

status = page.get_by_role('status')
print(status.text_content())

Queries such as text_content do not wait for any particular value; they return what is on the page right now. Immediately after the click, the status says Loading....

expect(status).to_have_text('Loaded 4 books')

The expect function creates web-first assertions. The to_have_text assertion repeatedly checks the element until it has the expected text or until the timeout expires (five seconds by default). This is the preferred way to wait for a state of the page, both in tests and in scripts.

$ python load_books.py
Loading...
Loaded 4 books
waited 1.9 s

Scraping a table

Because the browser executes JavaScript, Playwright can extract data that is not present in the HTML source. We read the books from the table rendered by the script.

scrape_table.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('http://localhost:8000/books.html')

    page.get_by_role('button', name='Load books').click()

    rows = page.locator('#books tbody tr')
    rows.first.wait_for()

    books = []

    for row in rows.all():
        title, author, price = row.locator('td').all_inner_texts()
        books.append({'title': title, 'author': author, 'price': float(price)})

    for book in books:
        print(book)

    total = sum(book['price'] for book in books)
    print(f'total: {total:.2f}')

    browser.close()

The program loads the books, converts each table row into a dictionary, and computes the total price.

rows = page.locator('#books tbody tr')
rows.first.wait_for()

The wait_for method waits until the element is visible. Unlike actions, methods such as all or count do not wait; calling rows.all right after the click would return an empty list.

for row in rows.all():
    title, author, price = row.locator('td').all_inner_texts()
    books.append({'title': title, 'author': author, 'price': float(price)})

For each row, we find its cells with a nested locator and unpack their texts into variables.

$ python scrape_table.py
{'title': 'Fluent Python', 'author': 'Luciano Ramalho', 'price': 59.99}
{'title': 'Python Crash Course', 'author': 'Eric Matthes', 'price': 39.99}
{'title': 'Effective Python', 'author': 'Brett Slatkin', 'price': 44.99}
{'title': 'Python Tricks', 'author': 'Dan Bader', 'price': 29.99}
total: 174.96

Filling forms

In the next example, we fill in and submit an order form.

site/order.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Order</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<h1>Order a book</h1>

<form id="order">
    <label for="name">Name</label>
    <input id="name" name="name" required>

    <label for="email">Email</label>
    <input id="email" name="email" type="email" placeholder="you@example.com" required>

    <label for="format">Format</label>
    <select id="format" name="format">
        <option value="paperback">Paperback</option>
        <option value="hardcover">Hardcover</option>
        <option value="ebook">E-book</option>
    </select>

    <label for="gift">Gift wrap</label>
    <input id="gift" name="gift" type="checkbox">

    <button type="submit">Send order</button>
</form>

<p id="summary" role="status"></p>

<script>
document.getElementById('order').addEventListener('submit', event => {
    event.preventDefault();
    const data = new FormData(event.target);
    const gift = data.has('gift') ? ' (gift wrapped)' : '';
    document.getElementById('summary').textContent =
        `Thank you, ${data.get('name')}! ` +
        `Your ${data.get('format')} copy${gift} is on its way to ${data.get('email')}.`;
});
</script>

</body>
</html>

The form has two text inputs, a drop-down list, and a checkbox. The script prevents the real submission and shows a summary below the form.

order.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('http://localhost:8000/order.html')

    page.get_by_label('Name').fill('Jane Doe')
    page.get_by_placeholder('you@example.com').fill('jane@example.com')
    page.get_by_label('Format').select_option('Hardcover')
    page.get_by_label('Gift wrap').check()

    print(page.get_by_label('Format').input_value())
    print(page.get_by_label('Gift wrap').is_checked())

    page.get_by_role('button', name='Send order').click()

    print(page.locator('#summary').inner_text())

    browser.close()

The program fills in the form, submits it, and prints the summary.

page.get_by_label('Name').fill('Jane Doe')
page.get_by_placeholder('you@example.com').fill('jane@example.com')

We find the text inputs by their label and placeholder. The fill method clears the field and sets its value. To simulate typing key by key, which fires keyboard events for each character, use press_sequentially.

page.get_by_label('Format').select_option('Hardcover')
page.get_by_label('Gift wrap').check()

The select_option method selects an option by its value or label, and check ticks a checkbox or a radio button.

print(page.get_by_label('Format').input_value())
print(page.get_by_label('Gift wrap').is_checked())

The input_value method returns the current value of an input, select, or textarea element; for the selected option it is the value of the value attribute, not the label.

page.get_by_role('button', name='Send order').click()

We submit the form by clicking on the button.

$ python order.py
hardcover
True
Thank you, Jane Doe! Your hardcover copy (gift wrapped) is on its way to jane@example.com.

Running JavaScript

The evaluate method runs JavaScript code in the page and returns the result to Python.

evaluate.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page(viewport={'width': 1024, 'height': 768})
    page.goto('http://localhost:8000/')

    size = page.evaluate('() => [window.innerWidth, window.innerHeight]')
    print(size)

    print(page.evaluate('([a, b]) => a * b', [6, 7]))

    lang = page.locator('html').evaluate('el => el.lang')
    print(lang)

    topics = page.locator('ul.topics li').evaluate_all(
        'items => items.map(e => e.textContent.toUpperCase())')
    print(topics)

    page.evaluate('document.querySelector("h1").textContent = "Book store"')
    print(page.locator('h1').text_content())

    browser.close()

The example evaluates several JavaScript expressions in the page.

size = page.evaluate('() => [window.innerWidth, window.innerHeight]')

If the code is a function, Playwright calls it and returns its result. The values are serialized, so JavaScript arrays become Python lists and objects become dictionaries. When the function returns a promise, Playwright waits for it.

print(page.evaluate('([a, b]) => a * b', [6, 7]))

The second argument is passed to the function. Only one argument is allowed, so we pass multiple values in a list.

lang = page.locator('html').evaluate('el => el.lang')

The evaluate method of a locator receives the matching element as the first argument.

topics = page.locator('ul.topics li').evaluate_all(
    'items => items.map(e => e.textContent.toUpperCase())')

The evaluate_all method receives an array of all matching elements.

page.evaluate('document.querySelector("h1").textContent = "Book store"')

A plain expression is evaluated as is. Here we modify the DOM of the page.

$ python evaluate.py
[1024, 768]
42
en
['PYTHON', 'JAVASCRIPT', 'RUST', 'GO', 'DATABASES']
Book store

User agent and HTTP headers

Settings such as the user agent, extra HTTP headers, locale, time zone, geolocation, or viewport are options of a browser context.

headers.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()

    context = browser.new_context(
        user_agent='Python program',
        extra_http_headers={'X-Request-Source': 'zetcode'},
        locale='sk-SK',
    )

    page = context.new_page()
    resp = page.goto('https://httpbin.org/headers')

    print(resp.status, resp.headers['content-type'])

    headers = resp.json()['headers']

    for name in ('User-Agent', 'X-Request-Source', 'Accept-Language'):
        print(f'{name}: {headers[name]}')

    browser.close()

We create a context with a custom user agent, an extra header, and the Slovak locale and check the headers that the server received. The httpbin.org service returns the request headers as JSON.

context = browser.new_context(
    user_agent='Python program',
    extra_http_headers={'X-Request-Source': 'zetcode'},
    locale='sk-SK',
)

page = context.new_page()

The new_context method creates an isolated browser session. Pages in different contexts do not share cookies, local storage, or cache, so one browser can simulate several independent users. The browser.new_page method used in the other examples is a shortcut that creates a context with a single page. The locale option affects navigator.language, the formatting of numbers and dates in JavaScript, and the Accept-Language header.

resp = page.goto('https://httpbin.org/headers')

print(resp.status, resp.headers['content-type'])

headers = resp.json()['headers']

The goto method returns a Response object. We get the status code, the response headers, and the body parsed as JSON.

Playwright also has predefined device descriptors, such as p.devices['iPhone 15'], which set the user agent, viewport, scale factor, and touch support. They are passed to new_context as keyword arguments: browser.new_context(**p.devices['iPhone 15']).

$ python headers.py
200 application/json
User-Agent: Python program
X-Request-Source: zetcode
Accept-Language: sk-SK

Intercepting requests

The route method intercepts network requests that match a URL pattern. A route handler can let the request continue, modify it, abort it, or fulfill it with a mocked response.

mock.py
from playwright.sync_api import sync_playwright, Route, expect

def mock_books(route: Route):
    route.fulfill(json=[
        {'title': 'Test book 1', 'author': 'John Doe', 'price': 1.5},
        {'title': 'Test book 2', 'author': 'Jane Doe', 'price': 2.5},
    ])

def block(route: Route):
    print('blocked', route.request.url)
    route.abort()

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    page.route('**/books.json', mock_books)
    page.route('**/*.css', block)

    page.goto('http://localhost:8000/books.html')
    page.get_by_role('button', name='Load books').click()

    expect(page.get_by_role('status')).to_have_text('Loaded 2 books')

    for row in page.locator('#books tbody tr').all():
        print(row.locator('td').all_inner_texts())

    browser.close()

We replace the data of the books page with mocked data and block the style sheet.

def mock_books(route: Route):
    route.fulfill(json=[
        {'title': 'Test book 1', 'author': 'John Doe', 'price': 1.5},
        {'title': 'Test book 2', 'author': 'Jane Doe', 'price': 2.5},
    ])

The fulfill method answers the request without contacting the server. The json option serializes the data and sets the Content-Type header. We could also set the status, headers, and body options, or fetch the real response with route.fetch and modify it.

def block(route: Route):
    print('blocked', route.request.url)
    route.abort()

The abort method makes the request fail. Blocking images, fonts, and style sheets speeds up scraping.

page.route('**/books.json', mock_books)
page.route('**/*.css', block)

The routes are registered before navigation. The patterns are globs where ** matches any characters including slashes; a compiled regular expression or a predicate function can be used as well.

$ python mock.py
blocked http://localhost:8000/style.css
['Test book 1', 'John Doe', '1.50']
['Test book 2', 'Jane Doe', '2.50']

Listening to events

A page emits events for network traffic, console messages, dialogs, downloads, errors, and more. We subscribe to them with the on method.

events.py
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    page.on('request', lambda req: print('>>', req.method, req.url))
    page.on('response', lambda resp: print('<<', resp.status, resp.url))
    page.on('console', lambda msg: print('console:', msg.type, msg.text))

    page.goto('http://localhost:8000/books.html')

    with page.expect_response('**/books.json') as resp_info:
        page.get_by_role('button', name='Load books').click()

    resp = resp_info.value
    print(len(resp.json()), 'books in', resp.url)

    expect(page.get_by_role('status')).to_contain_text('Loaded')

    browser.close()

The program logs all requests, responses, and console messages of the books page.

page.on('request', lambda req: print('>>', req.method, req.url))
page.on('response', lambda resp: print('<<', resp.status, resp.url))
page.on('console', lambda msg: print('console:', msg.type, msg.text))

Each handler receives an object describing the event: a Request, a Response, or a ConsoleMessage.

with page.expect_response('**/books.json') as resp_info:
    page.get_by_role('button', name='Load books').click()

resp = resp_info.value

The expect_response context manager waits for a response that matches the pattern. The action that triggers the request is performed inside the block, so the response cannot be missed. Similar methods exist for other events, for instance expect_request, expect_download, or expect_popup.

$ python events.py
>> GET http://localhost:8000/books.html
<< 200 http://localhost:8000/books.html
>> GET http://localhost:8000/style.css
<< 200 http://localhost:8000/style.css
>> GET http://localhost:8000/books.json
<< 200 http://localhost:8000/books.json
console: log rendered 4 rows
4 books in http://localhost:8000/books.json

Async API

The asynchronous API has the same classes and methods as the synchronous one; the methods are coroutines that must be awaited. It is useful when we control several pages concurrently, or when Playwright is used in an application that already runs an asyncio event loop. The synchronous API cannot be used inside a running event loop, for example in a Jupyter notebook.

load_async.py
import asyncio
import time

from playwright.async_api import async_playwright

async def load_books(browser, url):

    page = await browser.new_page()
    await page.goto(url)
    await page.get_by_role('button', name='Load books').click()

    status = page.get_by_role('status').filter(has_text='Loaded')
    await status.wait_for()

    text = await status.text_content()
    await page.close()

    return text

async def main():

    urls = ['http://localhost:8000/books.html'] * 3

    async with async_playwright() as p:

        browser = await p.chromium.launch()
        start = time.perf_counter()

        results = await asyncio.gather(*(load_books(browser, url) for url in urls))

        print(results)
        print(f'elapsed {time.perf_counter() - start:.1f} s')

        await browser.close()

asyncio.run(main())

The program loads the books page in three tabs concurrently.

from playwright.async_api import async_playwright

The asynchronous API is imported from the playwright.async_api module.

async with async_playwright() as p:

    browser = await p.chromium.launch()

The async_playwright function returns an asynchronous context manager. Methods that communicate with the browser are awaited.

status = page.get_by_role('status').filter(has_text='Loaded')
await status.wait_for()

Creating a locator is not awaited, because it does not communicate with the browser. Only the actions and queries are coroutines.

results = await asyncio.gather(*(load_books(browser, url) for url in urls))

The asyncio.gather function runs the three coroutines concurrently. Each page waits 1.5 seconds before it fetches the data, so loading the pages one after another would take more than 4.5 seconds. See Python async/await for more about coroutines.

$ python load_async.py
['Loaded 4 books', 'Loaded 4 books', 'Loaded 4 books']
elapsed 2.0 s

Testing with pytest-playwright

The pytest-playwright plugin integrates Playwright with the pytest testing framework. It is installed with pip install pytest-playwright. The plugin provides fixtures such as page, context, and browser, and command line options for choosing the browsers and the mode.

tests/test_bookshop.py
import re

from playwright.sync_api import Page, expect

def test_title(page: Page):
    page.goto('/')
    expect(page).to_have_title('Bookshop')

def test_topics(page: Page):
    page.goto('/')
    topics = page.locator('ul.topics li')
    expect(topics).to_have_count(5)
    expect(topics.first).to_have_text('Python')

def test_navigation(page: Page):
    page.goto('/')
    page.get_by_role('link', name='Order').click()
    expect(page).to_have_url(re.compile(r'/order\.html$'))
    expect(page.get_by_role('heading', level=1)).to_have_text('Order a book')

def test_order(page: Page):
    page.goto('/order.html')
    page.get_by_label('Name').fill('Jane Doe')
    page.get_by_label('Email').fill('jane@example.com')
    page.get_by_role('button', name='Send order').click()
    expect(page.get_by_role('status')).to_contain_text('Thank you, Jane Doe!')

def test_load_books(page: Page):
    page.goto('/books.html')
    page.get_by_role('button', name='Load books').click()
    expect(page.locator('#books tbody tr')).to_have_count(4)

We test the demo site: the title of the home page, the topics list, a navigation link, the order form, and the loading of the books.

def test_title(page: Page):
    page.goto('/')
    expect(page).to_have_title('Bookshop')

Each test receives a new page in a fresh browser context, so the tests are isolated from each other. The browser itself is shared by all tests of a session. The URL is relative to the base URL from the configuration file.

expect(topics).to_have_count(5)
expect(topics.first).to_have_text('Python')

Like to_have_text, the other assertions retry until the condition is met or the timeout expires.

expect(page).to_have_url(re.compile(r'/order\.html$'))

The page assertions accept a string or a regular expression.

pytest.ini
[pytest]
base_url = http://localhost:8000
filterwarnings =
    ignore::pytest.PytestRemovedIn10Warning

The configuration file sets the base URL of the site; it can also be given on the command line with --base-url. The second option silences a deprecation warning that the built-in base_url fixture of pytest-playwright 0.10 triggers with pytest 9.2.

By default, the tests run in headless Chromium. The --browser option, which can be repeated, selects the browsers. Other useful options are --headed, --slowmo, --device, --screenshot only-on-failure, and --tracing retain-on-failure.

$ pytest -v --browser chromium --browser firefox
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
configfile: pytest.ini
plugins: playwright-0.10.0
collecting ... collected 10 items

tests/test_bookshop.py::test_title[chromium] PASSED                      [ 10%]
tests/test_bookshop.py::test_topics[chromium] PASSED                     [ 20%]
tests/test_bookshop.py::test_navigation[chromium] PASSED                 [ 30%]
tests/test_bookshop.py::test_order[chromium] PASSED                      [ 40%]
tests/test_bookshop.py::test_load_books[chromium] PASSED                 [ 50%]
tests/test_bookshop.py::test_title[firefox] PASSED                       [ 60%]
tests/test_bookshop.py::test_topics[firefox] PASSED                      [ 70%]
tests/test_bookshop.py::test_navigation[firefox] PASSED                  [ 80%]
tests/test_bookshop.py::test_order[firefox] PASSED                       [ 90%]
tests/test_bookshop.py::test_load_books[firefox] PASSED                  [100%]

============================== 10 passed in 7.12s ==============================

Tracing

A trace records the actions of a browser context together with DOM snapshots, screenshots, network traffic, console messages, and the source code. It is the main tool for finding out why a script or a test failed.

record_trace.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch()
    context = browser.new_context()

    context.tracing.start(screenshots=True, snapshots=True, sources=True)

    page = context.new_page()
    page.goto('http://localhost:8000/order.html')
    page.get_by_label('Name').fill('Jane Doe')
    page.get_by_label('Email').fill('jane@example.com')
    page.get_by_role('button', name='Send order').click()

    context.tracing.stop(path='trace.zip')

    browser.close()

The program records a trace of filling in the order form and saves it to trace.zip.

context.tracing.start(screenshots=True, snapshots=True, sources=True)

Tracing is started on a browser context. The options enable a screencast, DOM snapshots before and after each action, and the source code of the script.

context.tracing.stop(path='trace.zip')

The trace is written to a zip archive when tracing stops. We open it with the playwright show-trace trace.zip command or upload it to trace.playwright.dev; the trace viewer runs locally in the browser and shows a timeline of the actions with the state of the page before and after each of them.

$ python record_trace.py
$ unzip -l trace.zip
Archive:  trace.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
    13876  2026-11-17 10:21   trace.trace
     3917  2026-11-17 10:21   trace.network
     2459  2026-11-17 10:21   screencast/page@42eb9b50fcb9f4560d128a221817d9d6-1794907294415.jpeg
     8759  2026-11-17 10:21   screencast/page@42eb9b50fcb9f4560d128a221817d9d6-1794907294448.jpeg
     9438  2026-11-17 10:21   screencast/page@42eb9b50fcb9f4560d128a221817d9d6-1794907294479.jpeg
     1257  2026-11-17 10:21   resources/8cb402ff0e65e003d231e0d2ed685f8523cfbb35.html
      339  2026-11-17 10:21   resources/d3eb6a7be95984f97e1687a1345dc6aca9371b8f.css
      224  2026-11-17 10:21   trace.stacks
      531  2026-11-17 10:15   src/a05a0220ba9f20de46eb3fc63a6fefc6659ca12c.py
---------                     -------
    40800                     9 files

Headed mode and slow motion

When writing a script, it helps to see what the browser does. The headless=False option opens a browser window and slow_mo slows down each operation by the given number of milliseconds.

headed.py
import time

from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch(headless=False, slow_mo=500)
    page = browser.new_page()

    page.goto('http://localhost:8000/order.html')

    start = time.perf_counter()

    page.get_by_label('Name').fill('Jane Doe')
    page.get_by_label('Email').fill('jane@example.com')
    page.get_by_role('button', name='Send order').click()

    print(f'three actions took {time.perf_counter() - start:.1f} s')
    print(page.evaluate('navigator.userAgent'))

    browser.close()

The program fills in the order form in a visible browser window, measures how long the three actions took, and prints the user agent.

browser = p.chromium.launch(headless=False, slow_mo=500)

Each of the three actions is delayed by half a second. A headed browser needs a graphical display; on a server without one, we can run the script with xvfb-run.

Note that the headed Chromium reports a regular Chrome user agent, while the headless browser in the previous examples identifies itself as HeadlessChrome. Some websites use this to detect bots.

Instead of writing locators by hand, we can let Playwright generate the code. The playwright codegen http://localhost:8000/ command opens a browser and an inspector window and records our clicks and typing as Python code. Calling page.pause() in a headed script stops it and opens the Playwright Inspector, where we can step through the actions and try locators.

$ python headed.py
three actions took 1.6 s
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/159.0.0.0 Safari/537.36

Source

Playwright for Python – documentation

Playwright for Python – Locators

Playwright for Python – Page API

Playwright for Python – Pytest plugin reference

In this article we have automated Chromium, Firefox, and WebKit in Python with Playwright. See also Python async/await, Python Selenium, Python web scraping, Python BeautifulSoup, and Python pytest.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.