The Playwright Python Async API (async_playwright and pytest-playwright-asyncio)

Everything in this course so far used Playwright’s sync API, which is the simplest choice for tests. Playwright Python also has an async API built on asyncio. You need it when your test code lives inside an async application (FastAPI, an async bot, an AI agent), when one script should drive many pages concurrently, or when your team’s code base is async already. In this lesson you will translate sync code to async, run pages concurrently with asyncio.gather, handle events and routes with async functions, avoid the common mistakes, and write async pytest tests with the official pytest-playwright-asyncio plugin.

Advertisement

📖 What You’ll Learn: sync vs async API and when to choose each, async_playwright and asyncio.run, the await rules (actions, expect, evaluate), what is not awaited (locators, page.on), translating sync code step by step, concurrent pages with asyncio.gather and a semaphore, async route handlers and event handlers, wait_for_event and expect_response in async code, installing pytest-playwright-asyncio and pytest-asyncio, loop scope settings, async fixtures and tests, and mistakes such as a missing await or mixing sync and async.


⚖️ Sync or Async?

Both APIs have the same classes and methods (Page, Locator, expect …) and drive the same browsers. The difference is how your Python code waits:

Sync API (playwright.sync_api) Async API (playwright.async_api)
Calls page.goto(url) await page.goto(url)
Runs in Normal functions async def functions inside an asyncio event loop
Concurrency One thing at a time per thread (use xdist for parallel tests) Many pages at once in one thread with asyncio.gather
pytest plugin pytest-playwright pytest-playwright-asyncio
Choose when Writing tests (the default for most teams) Your code is already async, or you need concurrency inside one process

📌 Note: This lesson uses its own virtual environment with pytest-playwright-asyncio and pytest-asyncio instead of pytest-playwright. Install one of the two pytest plugins per environment: both provide fixtures named page, context and browser.


🚀 Your First Async Script

📄 first_async.py

import asyncio

from playwright.async_api import async_playwright, expect


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("https://sqatools.in/dummy-ecommerce-website/")
        await expect(page.get_by_test_id("product-card").first).to_be_visible()
        print("title:", await page.title())
        print("cards:", await page.get_by_test_id("product-card").count())
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python first_async.py

🖥️ Output

title: Dummy E-commerce Website For Automation Practice | SQA Tools
cards: 12

Compare with the sync version from Lesson 3: the shape is identical; async with, async def and await are the only additions.


✍️ The await Rules

Everything that talks to the browser returns a coroutine and must be awaited. Things that only build descriptions do not:

Awaited Not awaited
await page.goto(...), await locator.click(), await locator.fill(...) page.get_by_role(...), page.locator(...), locator.filter(...), locator.first (they create locators)
await expect(locator).to_have_text(...) expect(locator) itself
await page.title(), await locator.count(), await locator.inner_text() page.url (a property)
await page.evaluate(...), await page.screenshot(...) page.on("console", handler) (registering a handler)

The most common async bug is a forgotten await. Python does not stop you; it just creates a coroutine that never runs:

📄 missing_await.py

import asyncio
import warnings

from playwright.async_api import async_playwright

warnings.simplefilter("always")


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        page.goto("https://sqatools.in/dummy-ecommerce-website/")      # BUG: no await
        print("url after goto:", page.url)
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python missing_await.py

🖥️ Output

url after goto: about:blank

C:\Users\you\playwright-python\missing_await.py:13: RuntimeWarning: coroutine 'Page.goto' was never awaited
  page.goto("https://sqatools.in/dummy-ecommerce-website/")      # BUG: no await
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

The URL is still about:blank and Python prints RuntimeWarning: coroutine ... was never awaited. Treat that warning as an error. Type checkers catch it before you run the code: Pyright (used by VS Code’s Pylance) reports an unused coroutine by default.


Advertisement

⚡ Concurrency: Many Pages at Once

The real power of async is doing several slow things at the same time in one process. asyncio.gather runs coroutines concurrently; while one page waits for the network, others make progress:

📄 concurrent_pages.py

import asyncio
import time

from playwright.async_api import BrowserContext, async_playwright, expect

SHOP = "https://sqatools.in/dummy-ecommerce-website/#/search/"
TERMS = ["earbuds", "course", "jeans", "watch", "laptop", "shirt"]


async def count_results(context: BrowserContext, term: str) -> tuple[str, int]:
    page = await context.new_page()
    await page.goto(SHOP + term)
    await expect(page.get_by_test_id("product-card").first).to_be_visible()
    n = await page.get_by_test_id("product-card").count()
    await page.close()
    return term, n


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()

        start = time.perf_counter()
        for term in TERMS:
            await count_results(context, term)                       # one after another
        sequential = time.perf_counter() - start

        start = time.perf_counter()
        results = await asyncio.gather(*(count_results(context, t) for t in TERMS))
        concurrent = time.perf_counter() - start

        print(dict(results))
        print(f"sequential {sequential:.1f}s, concurrent {concurrent:.1f}s")
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python concurrent_pages.py

🖥️ Output

{'earbuds': 1, 'course': 6, 'jeans': 6, 'watch': 4, 'laptop': 7, 'shirt': 12}
sequential 6.0s, concurrent 1.2s

asyncio.gather returns results in the same order as the coroutines you passed, whatever order they finish in.

For many pages, limit concurrency so the browser and the server are not overwhelmed. A semaphore allows at most N at a time:

limit = asyncio.Semaphore(4)

async def limited(context, term):
    async with limit:                       # at most 4 pages open at once
        return await count_results(context, term)

results = await asyncio.gather(*(limited(context, t) for t in many_terms))

💡 Tip: Concurrency inside one browser is great for scripts: crawling, link checks, data collection, warming caches. For test suites, pytest-xdist (Lesson 65) is still the simpler way to run tests in parallel, because each test stays a simple, isolated function.


🎧 Events and Routes in Async Code

Handlers can be normal or async functions. Route handlers that call Playwright must be async and await their calls:

📄 async_handlers.py

import asyncio

from playwright.async_api import Route, async_playwright, expect

CATALOG = """<ul id="list"></ul><script>
fetch('/wp-json/sqa-api/v1/products?per_page=3').then(r => r.json()).then(b => {
  document.getElementById('list').innerHTML = b.data.map(p => `<li>${p.name}</li>`).join('');
  console.log('rendered ' + b.data.length + ' products');
});
</script>"""


async def fake_products(route: Route):
    await route.fulfill(json={"data": [{"name": "Async Laptop"}, {"name": "Async Phone"}]})


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        page.on("console", lambda msg: print("console:", msg.text))           # sync handler is fine for logging
        await page.route("https://sqatools.in/pw-demo", lambda route: route.fulfill(body=CATALOG, content_type="text/html"))
        await page.route("**/sqa-api/v1/products*", fake_products)             # async handler

        async with page.expect_response("**/sqa-api/v1/products*") as info:
            await page.goto("https://sqatools.in/pw-demo")
        response = await info.value
        print("status:", response.status, "| body:", await response.json())
        await expect(page.locator("#list li")).to_have_text(["Async Laptop", "Async Phone"])
        await browser.close()


asyncio.run(main())

⌨️ Terminal

python async_handlers.py

🖥️ Output

console: rendered 2 products
status: 200 | body: {'data': [{'name': 'Async Laptop'}, {'name': 'Async Phone'}]}

Note async with page.expect_response(...) and await info.value: the waiting helpers from Lesson 52 become async context managers whose value is awaited.


Advertisement

🧪 Async Tests with pytest-playwright-asyncio

The official pytest-playwright-asyncio plugin provides async versions of the familiar fixtures (page, context, browser, browser_context_args …) and the same command-line options (--browser, --headed, --base-url, --tracing …). It builds on pytest-asyncio.

⌨️ Terminal

pip install pytest-playwright-asyncio pytest-asyncio

Configure pytest-asyncio so the browser and the tests share one event loop for the whole session:

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in
asyncio_mode = auto
asyncio_default_fixture_loop_scope = session
asyncio_default_test_loop_scope = session
# pytest 9 warns about how the plugin defines one fixture; harmless, so it is filtered
filterwarnings =
    ignore::pytest.PytestRemovedIn10Warning
  • asyncio_mode = auto treats every async def test_... as an asyncio test (otherwise each needs @pytest.mark.asyncio).
  • The two loop_scope = session settings matter: Playwright’s session-scoped browser lives in one event loop, and tests must run in that same loop.

📄 tests/test_async_shop.py

import asyncio

import pytest
from playwright.async_api import BrowserContext, Page, expect

SHOP = "/dummy-ecommerce-website/"


async def test_login(page: Page):
    await page.goto(SHOP + "#/login")
    await page.get_by_test_id("login-username").fill("testuser")
    await page.get_by_test_id("login-password").fill("Test@123")
    await page.get_by_test_id("login-button").click()
    await expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")


@pytest.mark.parametrize("term", ["earbuds", "course"])
async def test_search(page: Page, term):
    await page.goto(SHOP + "#/search/" + term)
    await expect(page.get_by_test_id("product-card").first).to_be_visible()


async def test_two_shoppers_at_once(context: BrowserContext, browser):
    """Two isolated users side by side: a guest and a logged-in shopper."""
    member_context = await browser.new_context(base_url="https://sqatools.in")
    guest, member = await context.new_page(), await member_context.new_page()

    async def log_in(p: Page):
        await p.goto(SHOP + "#/login")
        await p.get_by_test_id("login-username").fill("testuser")
        await p.get_by_test_id("login-password").fill("Test@123")
        await p.get_by_test_id("login-button").click()

    await asyncio.gather(guest.goto(SHOP), log_in(member))
    await expect(guest.get_by_test_id("account-button")).to_contain_text("Login")
    await expect(member.get_by_test_id("account-button")).to_contain_text("Hi, Test")
    await member_context.close()

⌨️ Terminal

pytest -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: asyncio-1.5.0, playwright-asyncio-0.10.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=session, asyncio_default_test_loop_scope=session
collecting ... collected 4 items

tests/test_async_shop.py::test_login[chromium] PASSED                    [ 25%]
tests/test_async_shop.py::test_search[chromium-earbuds] PASSED           [ 50%]
tests/test_async_shop.py::test_search[chromium-course] PASSED            [ 75%]
tests/test_async_shop.py::test_two_shoppers_at_once[chromium] PASSED     [100%]

============================== 4 passed in 7.12s ==============================

Async fixtures work the same way:

📄 tests/conftest.py

import pytest_asyncio
from playwright.async_api import Page


@pytest_asyncio.fixture
async def shop_home(page: Page) -> Page:
    await page.goto("/dummy-ecommerce-website/")
    return page

📄 tests/test_fixture.py

from playwright.async_api import Page, expect


async def test_cart_starts_empty(shop_home: Page):
    await expect(shop_home.get_by_test_id("cart-count")).to_have_text("0")

⌨️ Terminal

pytest tests/test_fixture.py -q

🖥️ Output

.                                                                        [100%]
1 passed in 2.37s

⚠️ Common Async Mistakes

Mistake Symptom Fix
Missing await “coroutine was never awaited”, steps silently skipped Await every browser call; enable linters
Calling sync API inside async code “It looks like you are using Playwright Sync API inside the asyncio loop” Use playwright.async_api everywhere in async code
time.sleep() in async code Blocks every page at once await asyncio.sleep() (or better, expect)
pytest-playwright and pytest-playwright-asyncio installed together Fixture conflicts, confusing errors One plugin per environment
Function-scoped event loop “attached to a different loop” errors Session loop scope as configured above
Unlimited gather Memory spikes, server rate limits A semaphore to cap concurrency

Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Convert this sync snippet to the async API:

page.goto(SHOP + "#/cart")
page.get_by_test_id("coupon-input").fill("SAVE10")
page.get_by_test_id("apply-coupon").click()
expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE10 applied.")
Show answer
await page.goto(SHOP + "#/cart")
await page.get_by_test_id("coupon-input").fill("SAVE10")
await page.get_by_test_id("apply-coupon").click()
await expect(page.get_by_test_id("coupon-message")).to_have_text("Coupon SAVE10 applied.")

Locators (page.get_by_test_id(...)) are not awaited; the actions and the assertion are.

Exercise 2: Write an async function titles(urls) that opens all URLs concurrently in one context, at most 3 at a time, and returns their titles in the same order.

Show answer
async def titles(context, urls):
    limit = asyncio.Semaphore(3)

    async def one(url):
        async with limit:
            page = await context.new_page()
            await page.goto(url)
            title = await page.title()
            await page.close()
            return title

    return await asyncio.gather(*(one(u) for u in urls))

Exercise 3: A teammate’s async test fails with “It looks like you are using Playwright Sync API inside the asyncio loop”. What did they do?

Show answer

They imported from playwright.sync_api (or used a sync helper) inside async code. Inside an event loop only the async API may be used: import Page, expect and friends from playwright.async_api and await the calls.

Exercise 4: Write an async route handler that adds a header X-Test: async to every request to **/sqa-api/** and continues it.

Show answer
async def add_header(route):
    await route.continue_(headers={**route.request.headers, "X-Test": "async"})

await page.route("**/sqa-api/**", add_header)

🧠 MCQ Quiz: The Async API: async_playwright

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which import gives you the async API?
  2. Which of these is NOT awaited?
  3. What happens if you forget await before page.goto(...)?
  4. What does asyncio.gather(*coros) return?
  5. How do you limit how many pages run at the same time?
  6. Which plugin provides async pytest fixtures for Playwright?
  7. Why should pytest-playwright and pytest-playwright-asyncio not be installed together?
  8. What does asyncio_mode = auto do?
  9. Why set the loop scope to session?
  10. In async code, how do you use expect_response?

Want a longer, timed test? Take the Module 13 mock interview (20 MCQs in 20 minutes).


Advertisement

❓ Frequently Asked Questions

🤔 Is the async API faster?

Not per action: the browser does the same work. It is faster when you run independent work concurrently in one process. For ordinary test suites, the sync API with pytest-xdist is just as fast and simpler.

🤔 Can I use Playwright’s async API with FastAPI or Django?

Yes. Inside async views or background tasks use async_playwright. Create the Playwright instance once (for example at application start-up) and reuse the browser; launching a browser per request is slow.

🤔 Do I need async for AI agents and MCP servers?

Most agent frameworks and the MCP Python SDK are async, so the async API fits naturally there. The next two lessons look at Playwright MCP and AI tools.

🤔 Can I mix sync tests and async tests in one project?

Not in the same environment with both pytest plugins. Keep separate test folders with separate virtual environments, or stay with one API.

🤔 Does tracing work with the async API?

Yes: await context.tracing.start(...) / await context.tracing.stop(path=...), and pytest-playwright-asyncio supports --tracing retain-on-failure like the sync plugin.


🏁 Summary

  • The async API mirrors the sync API; add async def, async with async_playwright() and await on every browser call.
  • Locators and expect(...) are built without await; actions, assertions, queries and evaluate are awaited.
  • asyncio.gather (with a semaphore) drives many pages concurrently in one process; handlers can be async.
  • pytest-playwright-asyncio plus pytest-asyncio provide async fixtures; set asyncio_mode = auto and session loop scopes, and keep it in its own environment.
  • Watch for missing awaits, sync API calls inside async code and blocking sleeps.

🎬 Watch the Playwright tutorial series on YouTube!

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