Playwright for Python automates web applications in Chromium, Firefox, and WebKit. For a standalone browser-automation script, use the playwright library directly; for an end-to-end test suite, start with the official pytest-playwright plugin, which supplies test fixtures and multi-browser configuration. This guide walks through installation, a first script and test, reliable locators, browser coverage, debugging, and API testing.
What is Playwright for Python, and which workflow should you choose?
Playwright is a Python library for controlling browser pages and testing web applications. It supports Chromium, Firefox, and WebKit, with both synchronous and asynchronous APIs. You can use it to navigate pages, interact with controls, inspect results, and automate browser workflows. The official installation guide recommends the official pytest plugin for end-to-end tests.
Use the library directly for a script or custom workflow
Choose the library when you need a standalone automation script, want to control browser contexts yourself, or are integrating browser operations into an application. You manage the browser lifecycle and decide how to organize setup, cleanup, and checks.
Use pytest-playwright for an end-to-end test suite
Choose pytest-playwright when your goal is repeatable tests. Its fixtures provide browser objects such as a page for each test, and the plugin supports browser configuration. Isolated contexts help keep cookies, storage, and other browser state in one test from contaminating another. The examples below use this route for tests and the direct library for a general script.
#1 Best Overall
How do I install Playwright for Python?
Install the Python package and its browser binaries as separate steps. Run these commands from your project environment:
For a standalone script
pip install playwright
playwright install
For pytest end-to-end tests
pip install pytest-playwright
playwright install
The second command downloads the browser binaries Playwright uses. The browser revisions are tied to Playwright releases, so when you update the package, rerun playwright install if the required binaries need updating. A package upgrade paired with stale browser binaries can cause launch failures. See the browser installation and configuration guide for current details.
Python and operating-system support can change. Check the live requirements in the official introduction rather than assuming an older platform matrix still applies. The official documentation also lists Poetry and uv installation approaches if those are how your project manages dependencies.
How do I write a first Playwright script?
The synchronous API is a straightforward starting point for a normal script. This example opens a page, prints its title, and closes the browser:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://playwright.dev")
print(page.title())
browser.close()
Put the code in a file such as check_title.py, then run python check_title.py. For longer-lived scripts, make sure browser cleanup happens even if an operation raises an exception; use a try/finally block or a context-management pattern appropriate to your program.
Rank #2
Use async when the surrounding application uses asyncio
Playwright offers an asynchronous API as well. Keep the operations consistently asynchronous and await browser actions; do not mix synchronous and asynchronous Playwright calls in one example or workflow.
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto("https://playwright.dev")
print(await page.title())
await browser.close()
asyncio.run(main())
Match the API to the execution model of your application. The library guide documents both forms. It also states that the Playwright API is not thread-safe: in a multithreaded environment, create a Playwright instance per thread. The async guide cautions that cancelling a task during a Playwright call is unsupported and has undefined behavior.
How do I use Playwright with pytest?
With pytest-playwright installed, write a test that accepts the plugin’s page fixture. This example follows the official getting-started pattern:
from playwright.sync_api import Page, expect
def test_get_started_link(page: Page):
page.goto("https://playwright.dev/")
page.get_by_role("link", name="Get started").click()
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
Save it as test_navigation.py and run pytest. Tests run headless by default and use Chromium unless configured otherwise. The plugin provides an isolated page and browser context per test, making it easier to avoid state leaking between test cases. Consult Writing tests for fixture and configuration details.
Assert the user-visible outcome
A test should verify the behavior that matters, not merely that a click did not raise an error. In this example, the heading assertion checks the destination state after navigation. Prefer assertions on visible content or another meaningful outcome of the workflow.
How do I select an element reliably?
Locators are Playwright’s central way to identify page elements. Locator actions and assertions can retry while waiting for the element and expected condition, which makes them more robust than selecting an element once and immediately assuming the page is ready.
Prefer selectors that describe the user-facing control
- Use role and accessible name for controls such as links and buttons, for example
page.get_by_role("button", name="Save"). - Use labels for form fields, or text and placeholders when those accurately identify the intended element.
- Use a test ID when your project deliberately treats that ID as a stable testing contract.
- Narrow a locator with filters or chain it within a page region when a name appears more than once.
CSS and XPath can be useful when there is a specific reason to use them, but selectors tied to incidental layout or element position are often brittle. The locator guide explains locator strategies and filtering.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsWait for conditions, not an arbitrary number of seconds
Before performing an action, Playwright waits for the locator to be actionable. Its web-first assertions retry until the expected condition is met or the assertion times out. Use these behaviors in place of fixed time.sleep() delays, which can make tests slow and still fail when a page takes longer than the chosen sleep. When a workflow truly depends on a specific event or state, use a wait tied to that condition.
How do I run tests in Firefox and WebKit?
Playwright supports Chromium, Firefox, and WebKit. Choose coverage based on the rendering engines your users rely on and the environments in which your application runs; a test passing in one browser does not by itself establish the same behavior in the others.
Install and configure the browsers you need
Browser binaries are installed separately from the Python package and track Playwright releases. The pytest plugin can be configured for multiple browsers; use the current browser guide and pytest setup instructions for the supported configuration and commands. Do not assume that branded browser channels are installed by default: check the current configuration options when a test specifically needs one.
For local development and CI, keep the Playwright package and browser binaries aligned, and make browser coverage an explicit choice in your test setup. Device emulation and browser channels are configuration choices, not a guarantee that every device or branded browser is present in a default install.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →How do I generate and debug tests?
Use Codegen to capture a first draft
Run playwright codegen https://example.com to open a browser and the Playwright Inspector. Interact with the page and Codegen records actions while suggesting locators, prioritizing roles, text, and test IDs. Treat the result as a draft: review the selectors, remove incidental steps, and add assertions for the behavior you actually intend to verify. See Generating tests.
Use traces to understand a failure
To enable tracing with pytest, the docs show:
pytest --tracing on
The retain-on-failure option keeps traces for failed tests while removing those from successful runs. Open a trace in Trace Viewer to inspect the action timeline, logs, source, network activity, and DOM snapshots; these can reveal what the test did and what state the page was in when it failed. The Trace Viewer guide explains how to open and explore traces.
Trace files can contain page content and test data, so handle them according to your project’s data practices. The official documentation says the browser-hosted viewer loads traces locally in the browser and does not transmit them externally; still apply your normal controls to trace artifacts stored or shared by your team.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Can Playwright test an API?
Yes. APIRequestContext sends HTTP(S) requests without loading a browser page. It is useful for testing an API directly, preparing server-side state before a UI test, or checking a postcondition after a browser action. This complements rather than replaces UI coverage when the behavior under test is a user’s interaction with the application.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Best Value
The API testing guide includes examples of request contexts and response checks. Keep API setup and UI assertions focused on their respective responsibilities: use requests to arrange or inspect server state, and browser interactions to verify what a user can do.
Common Playwright Python problems and fixes
- Browser launch fails after an upgrade: the installed browsers may not match the updated Playwright package. Run
playwright installin the same environment and consult the browser guide. - A locator times out: check that the locator matches the intended element, the accessible name or label is correct, and the expected page state actually occurred. Prefer a user-facing locator and a condition-based assertion over a sleep.
- A test passes locally but fails in another browser: confirm that the other browser’s binaries are installed and configured, then inspect a trace for the failing run. Chromium, Firefox, and WebKit are distinct coverage targets.
- A test behaves differently depending on run order: look for shared state such as cookies, storage, or server-side data. The pytest plugin’s per-test context isolation helps with browser state, but your test data may also need independent setup and cleanup.
- Generated code is hard to maintain: Codegen captures interactions; it does not decide which steps or assertions belong in a durable test. Replace incidental selectors, simplify the sequence, and assert the user-visible result.
- Concurrent code produces confusing behavior: do not share a Playwright instance between threads. Create one per thread; in async code, avoid cancelling a task while it is inside a Playwright call.
Or skip the browser setup
If your goal is to capture a page image or PDF rather than interact with it in a browser test, ScreenshotNeo provides a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF. See the API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with response headers reporting the page verdict and billing status. Its MCP server lets AI agents use screenshot, page-info, and PDF-capture tools. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month, with no card required.
Frequently Asked Questions
Is Playwright for Python free to use?
The cited Playwright documentation describes an open-source software library; it does not establish a paid license requirement for the workflows in this guide.
Can I use Playwright to automate a site without writing tests?
Yes. The direct library workflow can run browser automation as a standalone script; pytest is the test-suite option, not a requirement for every automation task.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

