What Is Playwright for Python? Sync API, Async API and pytest Explained

Playwright is a free, open-source browser automation library from Microsoft. Its Python package lets you drive real Chromium, Firefox and WebKit browsers from Python code, and the pytest-playwright plugin turns it into a complete test framework. This first lesson explains what Playwright for Python is, how it works under the hood, and which of its two APIs you will use in this course.

Advertisement

๐Ÿ“– What You’ll Learn: what Playwright for Python is, the browsers it supports, how the Python package talks to the browser, the sync API vs the async API, why tests use pytest with the pytest-playwright plugin, and how the Python version differs from Playwright with TypeScript.


๐ŸŽญ What Is Playwright?

Playwright is a library for automating web browsers. With a few lines of code you can open a page, click buttons, type into fields, read text and check that the page behaves the way users expect. Testers use it for end-to-end (E2E) UI testing, API testing, and browser tasks like taking screenshots or saving PDFs.

Microsoft maintains Playwright and publishes it for four languages: JavaScript/TypeScript, Python, Java and .NET. All four share the same browser engine and the same concepts (pages, locators, auto-waiting, assertions), so what you learn here carries over to the other languages.

The Python package is called playwright on PyPI. At the time of writing, the current version is 1.64.1 (released October 2026), and it needs Python 3.10 or newer.


๐ŸŒ Which Browsers Does It Support?

One Python API controls all three major browser engines:

  • Chromium, the engine behind Google Chrome and Microsoft Edge. You can also run the installed branded Chrome or Edge through a *channel*.
  • Firefox (Gecko engine).
  • WebKit, the engine behind Safari. This lets you test Safari behaviour even on Windows and Linux.

Playwright works on Windows, macOS and Linux, in headless mode (no visible window, the default) or headed mode (you watch the browser).


โš™๏ธ How Playwright for Python Works

When you run a Playwright script, three pieces work together:

  1. Your Python code calls methods such as page.goto() and locator.click().
  2. The Playwright driver, which ships inside the Python package (it includes its own Node.js runtime, so you do not install Node yourself), receives those calls.
  3. The browser is controlled by the driver over a fast, persistent connection, not over separate HTTP requests per command like classic WebDriver.

Because of this design, Playwright can listen to browser events (network requests, dialogs, console messages, new tabs) as they happen and wait for elements intelligently. This is where its famous auto-waiting comes from: before clicking, Playwright checks that the element is attached, visible, stable, enabled and able to receive the click.

๐Ÿ“ Note: The browsers are separate downloads. After installing the Python package you run playwright install once to download the browser builds that match your Playwright version. You will do this in the next lesson.


๐Ÿ”€ Sync API vs Async API

The Python package offers two complete, equivalent APIs. They have the same methods; the difference is how you call them.

The sync API

The sync API (playwright.sync_api) reads like normal Python: each line runs and finishes before the next one starts. Save this as sync_title.py:

๐Ÿ“„ sync_title.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:                     # 1. start Playwright
    browser = p.chromium.launch()                # 2. launch headless Chromium
    page = browser.new_page()                    # 3. open a new tab

    page.goto("https://sqatools.in/automation-practice-page/")   # 4. navigate
    print("Title:", page.title())                # 5. read the page title

    browser.close()                              # 6. close the browser

Line by line:

  1. sync_playwright() starts the Playwright driver. Using it in a with block makes sure it stops cleanly when the block ends, even if an error happens.
  2. p.chromium.launch() starts a Chromium browser. Swap chromium for firefox or webkit to change browser.
  3. browser.new_page() opens a fresh tab and returns a Page object, the object you use for almost everything.
  4. page.goto(url) loads the URL and waits for the page’s load event.
  5. page.title() returns the text of the <title> tag.
  6. browser.close() closes the browser and all its tabs.

Run it with python sync_title.py:

๐Ÿ–ฅ๏ธ Output

Title: Automation Practice Page - SQA Tools

The async API

The async API (playwright.async_api) is built on Python’s asyncio. Every Playwright call is awaited. Save this as async_title.py:

๐Ÿ“„ async_title.py

import asyncio

from playwright.async_api import async_playwright


async def main():
    async with async_playwright() as p:          # start Playwright (async version)
        browser = await p.chromium.launch()
        page = await browser.new_page()

        await page.goto("https://sqatools.in/automation-practice-page/")
        print("Title:", await page.title())

        await browser.close()


asyncio.run(main())                              # run the async function

What changed compared to the sync version:

  • The code lives inside an async def function, and asyncio.run(main()) runs it.
  • with becomes async with, and every Playwright call gets await in front of it.
  • The result is the same: Title: Automation Practice Page - SQA Tools.

Which one should you learn?

Sync APIAsync API
Importplaywright.sync_apiplaywright.async_api
StylePlain Python, no awaitasync def + await everywhere
Best forTest automation with pytest, scriptsApps already built on asyncio, running many pages concurrently
Used in this courseModules 1 to 12Module 13

For UI testing, the sync API is the standard choice. The pytest-playwright plugin is built on it, the official docs show it first, and the code is easier to read. You will learn the async API later, once the core skills are solid.

โš ๏ธ Watch out: Do not mix the two APIs in one script. Calling the sync API inside a running asyncio event loop raises an error that tells you to use the async API instead.


๐Ÿงช Playwright + pytest: The Test Framework

The playwright package is a library, not a test runner. It does not discover tests, produce pass/fail results or create reports by itself. In Python, that job belongs to pytest, the most popular Python testing framework.

Microsoft publishes an official pytest plugin, pytest-playwright (current version 0.10.0). Installing it gives you:

  • Ready-made fixtures such as page, context and browser. Each test receives a fresh, isolated page without writing any launch or close code.
  • Command-line options like --browser firefox, --headed, --slowmo, --tracing, --video and --screenshot.
  • Web-first assertions through expect(), which wait and retry until the condition is true.

Here is a preview of what a test looks like. You will write and run it yourself in Lesson 4:

๐Ÿ“„ test_preview.py

from playwright.sync_api import Page, expect


def test_practice_page_title(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

Notice what is missing: no sync_playwright(), no launch(), no close(). The page fixture handles all of that.


๐Ÿ†š Playwright Python vs Playwright TypeScript

If you have seen our Playwright TypeScript tutorial, the ideas are identical but some names and tools differ:

TopicTypeScriptPython
Test runnerPlaywright Test (npx playwright test)pytest with pytest-playwright (pytest)
Configplaywright.config.tspytest.ini / pyproject.toml + conftest.py fixtures
Method namescamelCase: getByRole, toHaveTextsnake_case: get_by_role, to_have_text
Asyncawait on every callNot needed with the sync API
Retries and parallel runsBuilt inPlugins: pytest-rerunfailures, pytest-xdist
Screenshot comparisonBuilt-in toHaveScreenshotNo built-in matcher (covered in Module 5)
AI test agents (planner, generator, healer)AvailableNot available for Python yet

โœ… Why Testers Choose Playwright for Python

  • Auto-waiting removes most time.sleep() calls and flaky waits.
  • One API for three engines, including WebKit on any operating system.
  • Isolated browser contexts give every test a fresh, cookie-free session in milliseconds.
  • Powerful tooling: Codegen records tests for you, the Inspector debugs them, and the Trace Viewer replays failures step by step.
  • Network control to mock APIs, block resources or record traffic.
  • Python’s ecosystem: pytest, data libraries, and easy reading of JSON, CSV and Excel test data.

โ“ Frequently Asked Questions

๐Ÿค” Is Playwright for Python free?

Yes. Playwright and pytest-playwright are open source under the Apache 2.0 license.

๐Ÿค” Do I need Node.js to use Playwright with Python?

No. The Python package bundles the driver and the runtime it needs. You only install Python packages and then the browsers with playwright install.

๐Ÿค” Is Playwright better than Selenium for Python?

Both are good tools. Playwright gives you auto-waiting, browser contexts, network mocking and tracing out of the box, while Selenium has a longer history and wider grid support. Read Playwright vs Selenium vs Cypress for a detailed comparison.

๐Ÿค” Should I learn the sync or async API first?

Start with the sync API. It is what pytest-playwright uses and what you will use for day-to-day testing. The async API uses the same methods with await, so switching later is easy.


๐Ÿ Summary

  • Playwright for Python automates Chromium, Firefox and WebKit from Python 3.10+.
  • The package bundles its own driver; browsers are installed separately with playwright install.
  • It has a sync API (used for testing in this course) and an equivalent async API.
  • pytest plus the official pytest-playwright plugin provides fixtures, CLI options and the test runner.

Next, you will set up Python, a virtual environment, Playwright, pytest and VS Code on your machine.

๐ŸŽฌ Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Leave a Comment