Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To automate browser tests with Python, install Playwright and its pytest plugin, install the matching browser binaries, then write test_*.py tests using pytest fixtures, user-facing locators, and web-first assertions. Start with headless Chromium for quick feedback; add Firefox, WebKit, or branded browsers when your product’s browser support requires them. Playwright also works as a general browser-automation library, but its official Python guidance recommends the pytest plugin for end-to-end testing.
Install Playwright for Python
There are two separate installation steps: install the Python packages, then download the browser binaries that match the installed Playwright release. Installing or upgrading the package without installing its browsers can leave tests unable to launch a browser.
Create an isolated environment and install the packages
python -m venv .venv
# macOS or Linux:
source .venv/bin/activate
# Windows PowerShell:
# ..venvScriptsActivate.ps1
python -m pip install --upgrade pip
python -m pip install pytest-playwright
The pytest plugin brings in Playwright for Python. Install the browser binaries after the package installation:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →playwright install
On supported Linux CI images, missing operating-system libraries may also prevent a browser from starting. The CLI offers an OS-dependency option:
#1 Best Overall
playwright install --with-deps
Use that option in an environment where you have permission to install system packages. The supported operating systems and Python versions depend on the specific Playwright release: the introductory documentation has listed Python 3.8+, while later release notes say Python 3.8 is no longer supported. Do not treat an older minimum as current for every version. Pin Playwright in your project and check the documentation for that release.
Keep package and browser versions aligned
Each Playwright version expects specific browser binaries. When you upgrade Playwright, run playwright install again in the same environment and update the CI setup accordingly. For reproducible runs, pin the Python package versions in your dependency file or lockfile rather than allowing CI to install an unbounded latest release.
Write an isolated pytest browser test
Create a file whose name begins with test_, such as test_checkout.py. The plugin supplies a page fixture, which represents a page in an isolated browser context. The context separates test state such as cookies and storage, helping prevent one test’s session from leaking into another.
from playwright.sync_api import expect
def test_homepage_has_a_working_sign_in_link(page):
page.goto("https://example.com")
sign_in = page.get_by_role("link", name="Sign in")
expect(sign_in).to_be_visible()
expect(sign_in).to_have_attribute("href", "/login")
Replace the example URL and expected link with a route and outcome from your own application. Run it with:
Rank #2
pytest
The plugin’s documented default is headless Chromium. A test should describe an observable user outcome, not simply record that a sequence of clicks completed.
Prefer semantic locators and retrying assertions
Start with locators that match how a person identifies the control: accessible role and name, visible text, or an explicit test ID. For example, page.get_by_role("button", name="Place order") expresses more intent than a selector tied to a long CSS class chain. Use a test ID when the interface has no useful accessible name or text and your team deliberately maintains a stable testing hook.
Use Playwright’s expect assertions for changing page state. Assertions such as to_be_visible() and to_have_text() retry while the expected condition is not yet true, within the configured timeout. This is generally more reliable than checking immediately after navigation or adding a fixed sleep to every test. A sleep can make a slow test slower without ensuring the relevant condition has occurred.
Use Codegen to discover interactions, then edit the test
Playwright Codegen opens the site and an Inspector window, records interactions, and suggests locators. Start it against the route you need to explore:
playwright codegen https://example.com
Codegen prioritizes role, text, and test-ID locators. It can also save or load authentication state, which is useful when the flow begins after sign-in. Treat the generated script as a draft: remove incidental navigation and clicks, check that each locator describes the intended control, and add an assertion for the business outcome—such as a confirmation heading or updated account state. A recorded click alone does not prove that the application completed the action.
Run Chromium, Firefox, and WebKit where they matter
Use the browser that gives your team the fastest useful feedback as the default, then expand coverage based on the browsers and operating systems your customers actually use. Playwright supports its bundled Chromium, Firefox, and WebKit builds. It can also launch branded Chrome and Microsoft Edge channels, and offers emulation for mobile and tablet device profiles.
| Target | When to include it | Important distinction |
|---|---|---|
| Bundled Chromium | Fast default feedback and broad Chromium-engine coverage. | Convenient bundled build; it may be ahead of stable Chrome or Edge. |
| Playwright Firefox | Check behavior in the Firefox engine. | Playwright uses a patched Firefox build, not necessarily the same setup as a user’s installed browser. |
| Playwright WebKit | Check Safari-oriented rendering and behavior. | It is a Safari-oriented WebKit option, not branded Safari. |
| Branded Chrome or Edge | Test against the branded browser channel or an enterprise-relevant browser setup. | Requires the corresponding channel to be available in the environment. |
Choose targets by standards and rendering risk, fidelity to user browsers, media-codec needs, operating-system availability, startup time, CI cost, and enterprise browser policies. Device emulation is useful for viewport and device-profile behavior, but it is not a substitute for testing on the actual mobile browser and hardware combinations that matter to your product.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Run a browser matrix with pytest
The plugin accepts repeated --browser flags for a matrix run. Install the corresponding binaries first:
playwright install chromium firefox webkit
pytest --browser chromium --browser firefox --browser webkit
A matrix multiplies browser launches and execution time, so begin with a small high-value test set if running every test in every browser is too costly. Keep the broader suite for scheduled or pre-release runs if that better fits the project’s feedback needs.
Use headed mode when visual context helps
To watch the browser interact with the page, run:
pytest --headed
Headed mode helps reveal issues such as an unexpected redirect, a modal covering a control, or a page that never reaches the expected state. It does not by itself make a failing test more reliable; use it to observe the failure, then fix the locator, synchronization condition, environment, or application behavior causing it.
Capture traces and debug failures
When a failure is hard to reproduce, retain a trace on failure and open it in Trace Viewer. The trace records an action timeline and page state that can help show what happened before the assertion failed.
pytest --tracing retain-on-failure
Open a saved trace with the Playwright CLI:
playwright show-trace path/to/trace.zip
The pytest plugin also provides tracing controls; configure them through the plugin’s CLI options so that traces are kept for the runs you need to inspect. Avoid recording traces for every successful run indefinitely if storage or artifact-retention limits matter to your CI system.
Best Value
A practical failure investigation order
- Read the failed assertion and URL. Check whether the test reached the expected page and whether the observed state is actually the application’s intended outcome.
- Inspect the trace timeline. Find the last successful action, navigation, or state change and inspect the page state around the failure.
- Re-run headed if the visual sequence is unclear. Watch for overlays, redirects, missing content, or a control that differs from the locator’s expectation.
- Enable API debugging output when necessary. Playwright’s API debugging output can expose details useful for diagnosing browser automation behavior.
- Fix the cause, not just the timeout. Use a locator that identifies the right control, wait for the relevant visible state, or address an environmental dependency instead of routinely extending every timeout.
Common Playwright Python problems and fixes
| Symptom | Likely cause | What to do |
|---|---|---|
| Browser executable is missing or cannot launch | The package was installed or upgraded but matching browser binaries were not installed; system dependencies may also be absent on Linux. | Run playwright install after installing or upgrading. On supported Linux environments, consider playwright install --with-deps. |
| A test passes locally but fails in CI | Different package/browser versions, missing OS libraries, or a page state reached at a different speed. | Pin package versions, reinstall matching binaries in CI, inspect a failure trace, and assert on the required state rather than relying on fixed delays. |
| Locator times out or matches the wrong control | The locator is ambiguous, tied to incidental markup, or does not reflect the accessible name or text shown to the user. | Inspect the page and choose a more specific role/name, text, or maintained test ID. Add an assertion that makes the desired result explicit. |
| Test behaves differently in Firefox or WebKit | Browser engines can render or behave differently; the test may also rely on an assumption specific to Chromium. | Reproduce on the failing target, inspect the trace, and decide whether the discrepancy is a product defect, a test assumption, or a browser-specific constraint. |
| Headed mode cannot start in a headless CI environment | The environment may not provide the display setup required for a visible browser. | Use the default headless run in that environment, or configure a suitable display environment before opting into headed execution. |
| Tests interfere with each other | State may be shared outside the isolated page/context, for example through external test data or shared accounts. | Use isolated test data and avoid concurrent tests mutating the same account or resource. |
Or skip the browser setup
For a one-off website screenshot rather than an interactive test, ScreenshotNeo is a separate screenshot API and MCP server—not a replacement for pytest assertions or Playwright browser testing. Its single GET request can return a PNG, JPEG, WebP, or PDF, and its options include full-page capture and CSS-selector element capture. Cookie banners are accepted and more than 60 known consent platforms, newsletter popups, and chat widgets are removed before the shot; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers indicate the page verdict and billing status. AI agents can use its MCP tools to take screenshots, get page information, and capture PDFs.
Here is a Python request using the ScreenshotNeo API:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for the request options and response details. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallFAQ
Can Playwright Python be used without pytest?
Yes. Playwright exposes both synchronous and asynchronous Python APIs and can be used as a general browser-automation library. The pytest plugin is the recommended starting point for end-to-end test suites.
Should every test run in every supported browser?
Not necessarily. Match the matrix to your users and risk: use a fast default for routine feedback, then allocate cross-browser runs to flows where engine differences could affect users.
Is Playwright WebKit the same as Safari?
No. It is Playwright’s Safari-oriented WebKit target, not branded Safari. Treat results as useful WebKit coverage, not proof that every Safari configuration behaves identically.
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.

