What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright for Python lets you control Chromium, Firefox, and WebKit from code. The quickest route to a working result is a small synchronous script; for a maintainable end-to-end suite, use the official pytest-playwright plugin. This tutorial installs both the Python package and its browser binaries, builds a first test, then shows locator, assertion, async, cross-browser, debugging, and reliability patterns.

Choose your Python Playwright route

Route Best for What you get
Standalone library script Learning browser control, one-off automation, data capture Explicit browser and context lifecycle in one Python file
pytest-playwright End-to-end and regression test suites page fixture, isolated contexts, assertions, and browser configuration

Playwright’s documentation says it “was created specifically to accommodate the needs of end-to-end testing.” For a test suite, start with the official pytest plugin; use the standalone version first when you want to understand the underlying API.

Prerequisites and installation

Check the current Playwright Python installation guide for supported operating systems before setting up a new environment. The documentation’s current search result lists Python 3.8 or newer and platform requirements that include Windows 11 or Windows Server 2019 (or WSL), macOS 14 or later, and selected Debian and Ubuntu releases. These requirements can change.

Create an isolated environment

python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1

Install the library and browser binaries

pip install playwright
playwright install

pip install playwright installs the Python bindings; playwright install downloads the browser binaries separately. Omitting the second command commonly produces an executable-not-found error on the first launch.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Install the pytest plugin for a test project

pip install pytest-playwright
playwright install

The plugin’s fixtures create a fresh browser context for each test by default and support multiple browser configurations. Poetry and uv can install the same packages, but use the command form appropriate to your project’s environment and verify current package guidance in the official documentation.

Your first standalone script

Save this as first_playwright.py. It starts Playwright, launches Chromium, opens a stable public demo page, reads its title, and closes every resource.

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/python/")
    print(page.title())
    browser.close()

Run it with:

python first_playwright.py

sync_playwright() manages the Playwright driver. p.chromium selects an engine, new_page() creates a tab in a new context, and goto() waits for navigation to reach its normal load state. In a longer program, put browser creation in a try/finally block so an exception cannot leave processes running.

Turn the script into a pytest test

Create tests/test_home.py:

from playwright.sync_api import Page, expect


def test_home_page(page: Page):
    page.goto("https://playwright.dev/python/")
    expect(page).to_have_title("Playwright Python")
    expect(page.get_by_role("heading", name="Playwright enables reliable end-to-end testing for modern web apps.")).to_be_visible()

Run the test:

pytest

The page fixture is supplied by pytest-playwright. You do not launch or close the browser yourself; the plugin handles that lifecycle and isolates contexts between tests. To see the browser while developing, add the documented headed option:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
pytest --headed

Use a real application URL and an assertion that represents the outcome a user should see. A click without an assertion only proves that Playwright issued a click, not that the workflow succeeded.

Locators that survive UI changes

Playwright describes locators as “the central piece of Playwright’s auto-waiting and retry-ability.” A locator resolves against the current page when you use it, waits for actionability, and retries assertions while the page changes.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Prefer user-facing locators

page.get_by_role("button", name="Save")
page.get_by_label("Email address")
page.get_by_text("Order confirmed")

These express how a user or assistive technology identifies an element. They are generally less coupled to implementation details than a long CSS or XPath chain.

Use deliberate test IDs when accessible names are unsuitable

<button data-testid="checkout-submit">Complete purchase</button>
page.get_by_test_id("checkout-submit").click()

A test-ID contract is useful for complex widgets, but agree on the attribute and keep it stable. Avoid selectors such as div:nth-child(3) > span > button; a harmless layout change can break them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Filter and chain locators

card = page.get_by_role("listitem").filter(has_text="Pro plan")
card.get_by_role("button", name="Choose").click()

Chaining narrows the search without exposing the page’s internal DOM structure.

Web-first assertions instead of sleeps

Use expect assertions from playwright.sync_api. They wait for the expected condition and retry until it is satisfied or the assertion timeout expires.

from playwright.sync_api import expect

expect(page).to_have_url("https://example.com/account")
expect(page.get_by_role("heading", name="Dashboard")).to_be_visible()
expect(page.get_by_role("status")).to_have_text("Saved")

Do not replace these with time.sleep(2). Fixed sleeps make fast runs slower and still fail when a network response takes longer. If a particular transition has no user-visible state, wait for a meaningful selector or application event instead.

Form interaction and navigation example

This pattern fills a form, submits it, and verifies the resulting state. Adapt labels and expected text to your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
def test_sign_in(page: Page):
    page.goto("https://example.test/login")
    page.get_by_label("Email").fill("alice@example.com")
    page.get_by_label("Password").fill("correct-horse-battery-staple")
    page.get_by_role("button", name="Sign in").click()
    expect(page).to_have_url("https://example.test/dashboard")
    expect(page.get_by_role("heading", name="Dashboard")).to_be_visible()

Keep credentials out of source control. Supply test credentials through environment variables or your CI secret store, and use a test account whose data can be reset.

Sync versus async Python APIs

API Choose it when Shape
Sync A linear script or ordinary pytest test is the simplest fit Direct calls such as page.goto(...)
Async Your application already uses asyncio or concurrent async tasks Every Playwright operation is awaited

The official library guide recommends the async API for projects already built around asyncio. Do not mix sync Playwright calls into an active event loop.

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/python/")
        print(await page.title())
        await browser.close()


asyncio.run(main())

The browser and page lifecycle mirrors the synchronous version; the difference is that calls return awaitable operations.

Run Chromium, Firefox, and WebKit

The Python library can launch all three engines. Chromium is a practical first exercise; add Firefox and WebKit when your product’s browser support requires cross-engine coverage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from playwright.sync_api import sync_playwright

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("https://playwright.dev/python/")
        print(browser_type.name, page.title())
        browser.close()

With pytest-playwright, select a browser from the command line:

pytest --browser chromium
pytest --browser firefox
pytest --browser webkit

Run each browser in CI when compatibility is important rather than assuming that one engine represents all users.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Debugging failed tests

Browser executable is missing

Symptom: a launch error says an executable cannot be found. Fix: run playwright install in the same environment where pytest or Python runs. In CI, make browser installation an explicit setup step.

Locator timeout

Likely causes: wrong accessible name, the element is inside an iframe, navigation has not reached the expected page, or the selector is brittle. Inspect the rendered role/name, assert the URL or heading after navigation, and use a frame locator for iframe content. Do not immediately increase timeouts without finding the cause.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Assertion fails intermittently

Replace immediate reads and sleeps with web-first assertions. Confirm that the assertion describes a stable outcome, and wait for a visible status, URL, or heading that changes when the operation is complete.

Headless and headed behavior differ

Run pytest --headed locally to observe the page. Compare viewport, permissions, authentication state, and timing; do not “fix” a failure by adding arbitrary delays.

Tests affect one another

Keep data setup and cleanup inside each test. The pytest plugin’s context isolation helps, but records created in a shared external database still need deterministic cleanup or unique identifiers.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and maintenance

  • Reuse a browser process when your test framework supports it, while retaining isolated contexts and pages per test.
  • Keep locators close to the user-facing contract and review them when UI copy changes.
  • Use the narrowest assertion that proves the behavior; asserting an entire page snapshot for every step creates noisy failures.
  • Capture traces, screenshots, or video through your CI configuration when diagnosing failures, then retain only what your debugging policy requires.
  • Pin your project’s dependency policy and review Playwright’s release notes before upgrading browser binaries.
  • Run the smallest relevant test set during development and the full browser matrix in CI.

Or skip the browser setup

If your goal is a clean image or PDF rather than an interactive test, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One GET request returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo documentation for all options, including full-page lazy-image loading, CSS-selector element capture, dark mode, device presets, custom CSS or JavaScript, waits, request blocking, authentication headers, cookies, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture, and usage reporting.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can I use Playwright with an existing virtual environment?

Yes. Activate that environment, install the package there, and run playwright install before executing your script or tests.

Which browser should I learn first?

Use Chromium for the first exercise because it keeps the example simple, then add Firefox and WebKit when your supported-browser policy requires them.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do I need pytest to use Playwright for Python?

No. The standalone library works in a normal Python script; pytest-playwright is the recommended route for a structured end-to-end test suite.

The Bottom Line

Start with the synchronous script to learn the API, move to pytest-playwright for isolated maintainable tests, use role- and label-based locators with web-first assertions, and add Firefox and WebKit when your compatibility requirements demand them.

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.