Python Virtual Environments and pip for Playwright Test Projects

In Lesson 2 you created a virtual environment and installed pytest-playwright with one command. Now it is time to understand what really happens, because most “it works on my machine” problems in Python test projects come from packages and environments. You will learn how a virtual environment works, the pip commands you will use every week, how to pin versions for a team and CI, and how to diagnose the most common errors.

📖 What You’ll Learn: what a virtual environment contains, how to confirm which Python is running, the essential pip commands (install, show, list, uninstall, check, index versions), version specifiers, requirements.txt and a separate dev requirements file, upgrading Playwright safely, and fixing common environment errors.


🧠 What Is Inside a Virtual Environment?

A virtual environment is just a folder (we call it .venv) that contains:

  • a small copy of (or link to) the Python interpreter, in .venv\Scripts on Windows or .venv/bin on macOS and Linux;
  • its own site-packages folder (.venv\Lib\site-packages), where pip installs packages;
  • a pyvenv.cfg file that records which Python it was created from.

Activating the environment only changes your terminal’s PATH, so that typing python, pip, pytest or playwright runs the copies inside .venv. You can also skip activation and call the environment’s Python directly, which is handy in scripts and CI:

⌨️ Terminal

.venv\Scripts\python -m pytest

📝 Note: The browsers are not inside the virtual environment. playwright install puts them in a shared per-user cache (for example %USERPROFILE%\AppData\Local\ms-playwright on Windows), so several environments that use the same Playwright version share one download.


🔍 Which Python Am I Running?

Half of all environment problems come from running a different Python than you think. Ask Python itself:

⌨️ Terminal

python -c "import sys; print(sys.prefix); print(sys.executable)"

Inside a freshly created .venv in C:\pwv\exp9, the output is:

🖥️ Output

C:\pwv\exp9\.venv
C:\pwv\exp9\.venv\Scripts\python.exe
  • sys.prefix is the root of the active environment. If it points at your project’s .venv, you are in the right place.
  • sys.executable is the full path of the running interpreter.
  • python -c "..." runs a one-line program without creating a file.

The same check works from inside a test, which is useful when CI behaves differently from your laptop. Save it as check_env.py:

📄 check_env.py

import sys
from importlib.metadata import version

print("Python:", sys.version.split()[0])
print("Inside a virtual environment:", sys.prefix != sys.base_prefix)
print("playwright:", version("playwright"))
print("pytest-playwright:", version("pytest-playwright"))
  • sys.base_prefix is the Python the environment was created from. When it differs from sys.prefix, you are inside a virtual environment.
  • importlib.metadata.version("name") reads the installed version of any package.

🖥️ Output

Python: 3.15.1
Inside a virtual environment: True
playwright: 1.64.1
pytest-playwright: 0.10.0

🧰 The pip Commands You Will Actually Use

Always run pip as python -m pip .... It guarantees that the pip belongs to the Python you mean.

CommandWhat it does
python -m pip install pytest-playwrightInstall the latest version and its dependencies
python -m pip install "pytest-playwright==0.10.0"Install an exact version
python -m pip install --upgrade playwrightUpgrade to the newest version
python -m pip install -r requirements.txtInstall everything listed in a file
python -m pip listList installed packages and versions
python -m pip show playwrightDetails of one package, including what it requires
python -m pip uninstall -y greenletRemove a package without asking for confirmation
python -m pip checkVerify that every package’s dependencies are installed and compatible
python -m pip index versions pytest-playwrightList the versions available on PyPI
python -m pip freezePrint installed packages as name==version lines

A brand-new environment contains only pip itself:

🖥️ Output

Package Version
------- -------
pip     26.2.2

After installing, pip show explains how packages depend on each other:

🖥️ Output

Name: playwright
Version: 1.64.1
Summary: A high-level API to automate web browsers
Home-page: https://github.com/Microsoft/playwright-python
Author: Microsoft Corporation
License-Expression: Apache-2.0
Location: C:\pwv\exp9\.venv\Lib\site-packages
Requires: greenlet, pyee
Required-by: pytest-playwright
  • Requires lists what playwright needs (greenlet and pyee).
  • Required-by shows that pytest-playwright depends on it.

pip check is a quick health check. In a healthy environment it prints No broken requirements found.. To see it catch a problem, we uninstalled greenlet on purpose:

🖥️ Output

playwright 1.64.1 requires greenlet, which is not installed.

Reinstalling from requirements.txt repaired the environment, and pip check was happy again.


📌 Version Specifiers and requirements.txt

A requirements file lists one package per line, with an optional version rule:

LineMeaning
pytest-playwrightAny version (whatever is newest today)
pytest-playwright==0.10.0Exactly this version
playwright>=1.64,<2At least 1.64 but below 2.0
pytest~=9.2Compatible release: 9.2 or newer, but below 10

For test projects, exact pins (==) are the safest choice: everybody, including CI, runs exactly the versions you tested with. Create requirements.txt:

📄 requirements.txt

pytest-playwright==0.10.0
playwright==1.64.1
pytest==9.2.0

Pin the main packages yourself, or generate a complete list (including dependencies such as greenlet) with python -m pip freeze > requirements.txt. Then anyone can recreate the environment:

⌨️ Terminal

python -m venv .venv
.venv\Scripts\python -m pip install -r requirements.txt
.venv\Scripts\playwright install

Separate runtime and development requirements

Larger projects keep tools that only developers need (linters, formatters, type checkers) in a second file that includes the first one:

🖥️ Output

# requirements-dev.txt
-r requirements.txt
mypy
ruff

The line -r requirements.txt pulls in the main file, so developers run pip install -r requirements-dev.txt while CI can install only requirements.txt. Pin the dev tools with == too, using the versions your team has agreed on.


⬆️ Upgrading Playwright Safely

  1. Check what is available: python -m pip index versions playwright.
  2. Upgrade in your environment: python -m pip install --upgrade playwright pytest-playwright.
  3. Download the matching browsers: playwright install (each Playwright version needs its own browser builds).
  4. Run the whole suite. Read the Playwright release notes for behaviour changes.
  5. Update the pinned versions in requirements.txt and commit them, so CI upgrades in the same step.

🩺 Common Errors and Fixes

SymptomLikely causeFix
ModuleNotFoundError: No module named 'playwright'Running a Python without Playwright (environment not active)Activate .venv, or run .venv\Scripts\python -m pytest
pytest runs, but plugins or options are missingThe pytest command belongs to another PythonUse python -m pytest; check sys.executable
“Executable doesn’t exist” when a browser launchesBrowsers not downloaded for this Playwright versionRun playwright install
Works locally, fails in CI after a new releaseUnpinned versionsPin versions in requirements.txt
Activation blocked in PowerShellScript execution policySet-ExecutionPolicy -Scope CurrentUser RemoteSigned

🏋️ 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: Write the commands that show which Python is running, list installed packages, and show the installed version of playwright.

Show answer
python -c "import sys; print(sys.executable)"
pip list
pip show playwright

Exercise 2: Split dependencies into requirements.txt (runtime) and requirements-dev.txt (adds linting tools) so that the dev file includes the runtime file.

Show answer
# requirements.txt
playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
# requirements-dev.txt
-r requirements.txt
ruff>=0.6

pip install -r requirements-dev.txt installs both.

Exercise 3: Describe the safe steps to upgrade Playwright in a project.

Show answer

Read the release notes, then pip install -U playwright pytest-playwright (or change the pins), run playwright install to fetch the matching browsers, run the full suite, fix any failures, and commit the updated requirements.txt together with the code changes.


🧠 MCQ Quiz: Virtual Environments and pip

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. What does a virtual environment contain?
  2. How do you check which Python interpreter is active?
  3. What does pip show playwright display?
  4. What does playwright>=1.60,<2 mean?
  5. Which command checks installed packages for broken dependencies?
  6. What does -r requirements.txt inside another requirements file do?
  7. After upgrading the playwright package, what must you also run?
  8. Should the .venv folder be committed to Git?
  9. pip install puts packages into the system Python instead of the venv. What is the likely cause?
  10. Which command lists the versions of a package available on PyPI?

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


❓ Frequently Asked Questions

🤔 Can I move or rename a virtual environment folder?

Not reliably: the scripts inside contain absolute paths. Delete it and create a new one; with a requirements file that takes a minute.

🤔 Should I use venv, conda, poetry or uv?

All of them create isolated environments. This course uses the built-in venv and pip because they come with Python and work everywhere. If your team already uses another tool, the Playwright steps are the same.

🤔 Does each project need its own browsers?

No. Browsers live in a shared cache per Playwright version, so projects on the same version reuse them.

🤔 Why python -m pip instead of pip?

python -m pip always runs the pip of that exact Python. A bare pip might belong to a different installation on your PATH.


🏁 Summary

  • A virtual environment is a folder with its own interpreter and site-packages; activation only changes PATH.
  • Check sys.prefix and sys.executable whenever imports behave strangely.
  • Use python -m pip for install, show, list, check and index versions.
  • Pin exact versions in requirements.txt, keep dev tools in requirements-dev.txt, and re-run playwright install after every upgrade.

Next, you will add type hints to your test code so your editor can auto-complete Playwright methods and catch mistakes before you run anything.

🎬 Watch the Playwright tutorial series on YouTube!

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

Python Modules, Packages and Imports for Playwright Test Projects

As soon as a test project grows beyond one file, you split code into modules: page objects in one place, test data in another, helpers in a third. Python’s import system connects them. In this lesson you will learn how modules and packages work, which import style to use, how to lay out a Playwright project, and how to fix the ModuleNotFoundError that almost every pytest beginner meets.

📖 What You’ll Learn: what a module and a package are, import styles (import, from … import, aliases), what __init__.py does, the if __name__ == “__main__” guard, a clean Playwright project layout, why plain pytest cannot find your pages package, and two reliable fixes (a root conftest.py or pythonpath in pytest.ini).


📦 Modules: One File, One Purpose

A module is simply a .py file. Everything defined in it (variables, functions, classes) can be imported into another file. Create utils/helpers.py:

📄 utils/helpers.py

"""Small helpers shared by many tests."""

BASE_URL = "https://www.saucedemo.com/"


def full_url(path: str) -> str:
    """Join the base URL and a path such as 'inventory.html'."""
    return BASE_URL + path.lstrip("/")


def price_to_float(text: str) -> float:
    """Convert '$29.99' to 29.99."""
    return float(text.replace("$", "").strip())


if __name__ == "__main__":
    # Runs only when this file is executed directly, not when it is imported
    print(full_url("/inventory.html"))
    print(price_to_float("$29.99"))
  • BASE_URL, full_url and price_to_float are now reusable from any test.
  • The text in triple quotes right under a def is a docstring; editors show it when you hover over the function.
  • path.lstrip("/") removes a leading slash so the URL never gets a double slash.

The if __name__ == "__main__" guard

Every module has a built-in variable __name__. When you run a file directly, Python sets it to "__main__"; when the file is imported, it is set to the module’s name (here "utils.helpers"). The guard lets a file contain quick self-checks that never run during an import:

⌨️ Terminal

python -m utils.helpers

🖥️ Output

https://www.saucedemo.com/inventory.html
29.99

python -m utils.helpers runs the module by its import name from the project folder, which is the most reliable way to run a module that lives inside a package.

A second small example shows the two values side by side (main_guard.py):

📄 main_guard.py

import utils.helpers

print("Imported module name:", utils.helpers.__name__)
print("This file's name:", __name__)

🖥️ Output

Imported module name: utils.helpers
This file's name: __main__

📥 Import Styles

There are three common ways to import, and each has its place:

import json                                   # 1. whole module
from utils.helpers import full_url, BASE_URL  # 2. specific names
from playwright.sync_api import Page, expect  # 2. the style you use in every test
import utils.helpers as h                     # 3. module with a short alias
  1. import json brings in the module; you write json.loads(...). This makes it obvious where each name comes from.
  2. from module import name brings names straight into your file; you write full_url(...). Use it for things you use often, such as Page and expect.
  3. as h gives a long module name a short alias.

⚠️ Watch out: Avoid from module import *. It imports every public name, hides where things come from, and can silently overwrite your own names.

Python looks for modules in a list of folders called sys.path: the folder of the script you run (or the current folder with python -m), then the virtual environment’s installed packages, then the standard library. If the folder that contains your package is not on that list, the import fails with ModuleNotFoundError.


🗂️ Packages: Folders of Modules

A package is a folder of modules. Traditionally it contains an __init__.py file, which can be empty. A typical Playwright project looks like this:

🖥️ Output

playwright-python-demo/
├── pytest.ini
├── conftest.py
├── pages/                  # package: page objects
│   ├── __init__.py
│   └── login_page.py
├── utils/                  # package: helpers and test data loaders
│   ├── __init__.py
│   └── helpers.py
└── tests/                  # test files (no imports from here)
    └── test_login.py
  • pages and utils are packages, so you import from them with dots: from pages.login_page import LoginPage.
  • __init__.py marks the folder as a regular package. It runs once when the package is first imported, so it is also a place for package-wide setup (most of the time it stays empty).
  • Since Python 3.3, a folder without __init__.py still works as a *namespace package*. Keeping an empty __init__.py is clearer and avoids surprises with tools, so this course always adds one.

Here is the page object and a test that uses it (pages/login_page.py and tests/test_login.py):

📄 pages/login_page.py

from playwright.sync_api import Page

from utils.helpers import full_url


class LoginPage:
    """Actions for the Sauce Demo login page."""

    def __init__(self, page: Page):
        self.page = page
        self.username = page.get_by_placeholder("Username")
        self.password = page.get_by_placeholder("Password")
        self.login_button = page.get_by_role("button", name="Login")

    def open(self) -> None:
        self.page.goto(full_url(""))

    def login(self, user: str, password: str) -> None:
        self.username.fill(user)
        self.password.fill(password)
        self.login_button.click()

📄 tests/test_login.py

import re

from playwright.sync_api import Page, expect

from pages.login_page import LoginPage
from utils.helpers import full_url, price_to_float


def test_login_with_page_object(page: Page):
    login = LoginPage(page)
    login.open()
    login.login("standard_user", "secret_sauce")
    expect(page).to_have_url(full_url("inventory.html"))


def test_backpack_price(page: Page):
    LoginPage(page).open()
    LoginPage(page).login("standard_user", "secret_sauce")
    price_text = page.locator("[data-test='inventory-item-price']").first.inner_text()
    assert price_to_float(price_text) == 29.99
    expect(page.locator(".title")).to_have_text(re.compile("Products"))
  • Imports are grouped in the order recommended by Python’s style guide (PEP 8): standard library (re), third-party packages (playwright), then your own project (pages, utils), with a blank line between groups.
  • The page object imports a helper from utils, and the test imports from both packages.

🚨 The Classic Error: ModuleNotFoundError: No module named ‘pages’

With exactly the layout above but without conftest.py and pytest.ini, running the pytest command fails during collection:

🖥️ Output

ImportError while importing test module 'C:\pwv\exp8\proj\tests\test_login.py'.
E   ModuleNotFoundError: No module named 'pages'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.12s

Why? By default pytest adds the test file’s own folder (tests/) to sys.path, not the project root. The pages folder is in the root, so Python cannot see it.

Interestingly, python -m pytest works in the same situation, because running Python with -m also puts the current folder on sys.path. That difference confuses many people: a suite passes on one machine and fails on another depending on how it was started. Use one of these fixes so both commands always work:

Fix 1 (recommended): tell pytest where your code lives. Add pythonpath to pytest.ini:

📄 pytest.ini

[pytest]
pythonpath = .
testpaths = tests

pythonpath = . adds the folder that contains pytest.ini (the project root) to sys.path before tests are imported. It is explicit and works no matter how pytest is started.

**Fix 2: put a conftest.py in the project root.** pytest adds the folder of each conftest.py to sys.path, so a root conftest.py (even an empty one) also fixes the import. You will add fixtures there anyway:

📄 conftest.py

# Shared fixtures go here (see the pytest fixtures lessons in Module 3)

We tested all the combinations with pytest 9:

Project setuppytestpython -m pytest
No conftest.py, no pythonpathModuleNotFoundErrorPasses
Empty conftest.py in the rootPassesPasses
pythonpath = . in pytest.iniPassesPasses

With the fixes in place, the tests pass:

⌨️ Terminal

pytest -q

🖥️ Output

..                                                                       [100%]
2 passed in 3.35s

💡 Tip: Never add sys.path.append(...) lines at the top of test files to fix imports. They break as soon as files move. pythonpath = . in one place is the clean solution.


↔️ Relative Imports

Inside a package, a module can import a sibling with a leading dot, for example from .login_page import LoginPage inside pages/__init__.py. Relative imports only work for modules that are imported as part of a package, not for files run directly as scripts. In test projects, absolute imports (from pages.login_page import LoginPage) are simpler and easier to read, so prefer them.


⚠️ Common Mistakes

  • Naming a file after a library. A file called playwright.py or pytest.py in your project shadows the real package, because the script’s own folder comes first on sys.path. You then get errors like ModuleNotFoundError: No module named 'playwright.sync_api'; 'playwright' is not a package. Never reuse library names for your files.
  • Circular imports. If a.py imports b.py and b.py imports a.py, one of them sees a half-loaded module. Move shared code into a third module.
  • Importing from test files. Tests should import from pages and utils, never from other test_*.py files. Shared things belong in packages or conftest.py.

🏋️ 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: Create a package pages with a module login_page.py that defines class LoginPage. Show the folder layout and the import line a test uses.

Show answer
project/
├── pages/
│   ├── __init__.py
│   └── login_page.py      # class LoginPage: ...
└── tests/
    └── test_login.py
from pages.login_page import LoginPage

Exercise 2: Running pytest gives ModuleNotFoundError: No module named 'pages'. Give two reliable fixes.

Show answer

(1) Add pythonpath = . to pytest.ini (or pythonpath = ["."] in pyproject.toml), which puts the project root on the import path. (2) Put a conftest.py in the project root, which makes pytest insert the root directory into sys.path (in its default import mode).

Exercise 3: Add a guard to helpers.py so that print(slugify("Hello World")) runs only when the file is executed directly, not when it is imported by a test.

Show answer
def slugify(text: str) -> str:
    return text.lower().replace(" ", "-")


if __name__ == "__main__":
    print(slugify("Hello World"))

🧠 MCQ Quiz: Modules, Packages and Imports for Test Projects

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. What is a module in Python?
  2. What makes a folder a regular package?
  3. Which import gives you LoginPage directly?
  4. What does import numpy as np do?
  5. When is __name__ == "__main__" true?
  6. Why should you avoid from module import *?
  7. Which setting tells pytest to add the project root to the import path?
  8. Why should tests not import fixtures from conftest.py?
  9. In a clean Playwright project, where do page objects usually live?
  10. What is a relative import?

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


❓ Frequently Asked Questions

🤔 Do I need __init__.py in the tests folder?

No. pytest collects tests without it. Some teams add it to allow test files with the same name in different folders; if you do, pytest uses the package name to tell them apart.

🤔 What is the difference between a module and a package?

A module is one .py file. A package is a folder of modules (usually with an __init__.py), imported with dotted names such as pages.login_page.

🤔 Why does my import work in VS Code but fail in the terminal?

VS Code’s Testing view may start pytest differently (for example from a different folder). Adding pythonpath = . to pytest.ini makes the result the same everywhere.

🤔 Where should test data files live?

In their own folder, such as test_data/, loaded by helper functions in utils. You will do this in Module 7.


🏁 Summary

  • A module is a .py file; a package is a folder of modules, usually with __init__.py.
  • Prefer import module or from package.module import Name; avoid import * and sys.path hacks.
  • Plain pytest adds the test file’s folder to sys.path, so from pages... import fails without help.
  • Fix it with pythonpath = . in pytest.ini (or a root conftest.py), and keep library names out of your file names.

Next, you will take a closer look at virtual environments and pip, so every machine runs your tests with exactly the same packages.

🎬 Watch the Playwright tutorial series on YouTube!

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

Playwright Codegen for Python: Record pytest Tests and Pick Locators

Codegen is Playwright’s test recorder. You click through your application in a real browser, and Playwright writes the Python code for every action as you go, including good locators. In this lesson you will record pytest tests, read the generated code line by line, add assertions from the recorder toolbar, and turn a raw recording into a clean, reliable test.

📖 What You’ll Learn: starting Codegen with the python-pytest target, saving recordings to a file, what the generated code means, the recorder toolbar (record, pick locator, assertions), emulating devices, languages and logins while recording, recording from inside a test with page.pause(), and cleaning up recorded code.


🎥 Start Recording

Activate your virtual environment and run:

⌨️ Terminal

playwright codegen --target python-pytest https://www.saucedemo.com/

Two windows open:

  1. A browser showing the URL. Everything you do here is recorded.
  2. The Playwright Inspector, which shows the generated code live.

--target python-pytest tells Codegen to write a pytest test function that uses the page fixture. Other Python targets are python (a sync script with sync_playwright, the default) and python-async (an asyncio script).

To save the recording straight into your project, add -o (or --output):

⌨️ Terminal

playwright codegen --target python-pytest -o tests/test_recorded_login.py https://www.saucedemo.com/

The file is written when you close the browser window.


📝 What Codegen Writes

We recorded this flow on Sauce Demo: click the Username field, type standard_user, click the Password field, type secret_sauce, click Login, click Add to cart for the backpack, then open the cart. Codegen produced exactly this:

📄 tests/test_recorded_login.py

import re
from playwright.sync_api import Page, expect


def test_example(page: Page) -> None:
    page.goto("https://www.saucedemo.com/")
    page.locator("[data-test=\"username\"]").click()
    page.locator("[data-test=\"username\"]").fill("standard_user")
    page.locator("[data-test=\"password\"]").click()
    page.locator("[data-test=\"password\"]").fill("secret_sauce")
    page.locator("[data-test=\"login-button\"]").click()
    page.locator("[data-test=\"add-to-cart-sauce-labs-backpack\"]").click()
    page.locator("[data-test=\"shopping-cart-link\"]").click()

Reading it line by line:

  • import re is always added, so you can use regular expressions in assertions. Page and expect are imported for the test.
  • def test_example(page: Page) -> None: is a normal pytest test. The -> None type hint just says the function returns nothing. Rename the function to describe the behaviour.
  • page.goto(...) is the URL you started with.
  • Each click and each typed value became one line. Codegen records the click into a field and the fill separately; the click is harmless but unnecessary, because fill() focuses the field itself.
  • This site gives its elements data-test attributes, so Codegen used them: [data-test="username"] is a CSS attribute selector. The \" sequences are just double quotes escaped inside a Python string.

⚠️ Watch out: The recording has no assertions. It proves the clicks did not crash, not that the app works. A test without an expect() is not a real test yet.


🎯 How Codegen Chooses Locators

Codegen looks at each element and picks the most stable, human-readable locator it can, roughly in this order: test-id attributes, then role plus accessible name, then text, placeholder or label, and CSS only as a fallback. On the SQA Tools practice page, which has no test-id attributes, we recorded typing a username, choosing Female, ticking Python, choosing India and clicking Submit:

import re
from playwright.sync_api import Page, expect


def test_example(page: Page) -> None:
    page.goto("https://sqatools.in/automation-practice-page/")
    page.get_by_role("textbox", name="Enter username").click()
    page.get_by_role("textbox", name="Enter username").fill("qa_learner")
    page.get_by_role("radio", name="Female").check()
    page.get_by_role("checkbox", name="Python").check()
    page.locator("#country").select_option("india")
    page.get_by_role("button", name="Submit").click()
  • get_by_role("textbox", name="Enter username") finds the input by its role and accessible name, which here comes from its placeholder text.
  • Clicking a radio button or checkbox was recorded as check(), which is more precise than click(): it only ticks, never unticks.
  • The dropdown has the id country, so Codegen used the CSS id selector #country, and it selected the option by its value (india), not its visible label (India).

If your app uses a different test-id attribute name, tell Codegen with --test-id-attribute:

⌨️ Terminal

playwright codegen --target python-pytest --test-id-attribute data-qa https://example.com

🧰 The Recorder Toolbar

The toolbar at the top of the browser window (and in the Inspector) has these tools:

ToolWhat it does
RecordStart or pause recording actions
Pick locatorHover over any element to see the locator Codegen would use; click to copy it into the Inspector
Assert visibilityClick an element to add expect(...).to_be_visible()
Assert textClick an element to add expect(...).to_contain_text(...), or to_have_text(...) when you keep the whole text
Assert valueClick an input to add expect(...).to_have_value(...)
Assert snapshotClick an element to add an accessibility-tree assertion (to_match_aria_snapshot)

Even if you write your tests by hand, Pick locator is extremely useful: it shows you the best locator for any element in seconds.


🧹 From Recording to a Real Test

Raw recordings are a starting point. Clean them up in four steps:

  1. Rename test_example to describe the behaviour.
  2. Delete the unnecessary click() before each fill().
  3. Add assertions after each important step (the recorder’s assert tools help).
  4. Prefer user-facing locators where they read better, and move hard-coded data into variables.

Here is the Sauce Demo recording after cleanup (tests/test_cart.py):

📄 tests/test_cart.py

import re

from playwright.sync_api import Page, expect


def test_user_can_add_backpack_to_cart(page: Page) -> None:
    # Log in
    page.goto("https://www.saucedemo.com/")
    page.locator("[data-test='username']").fill("standard_user")
    page.locator("[data-test='password']").fill("secret_sauce")
    page.locator("[data-test='login-button']").click()
    expect(page).to_have_url(re.compile(r".*/inventory\.html"))

    # Add the backpack to the cart
    page.locator("[data-test='add-to-cart-sauce-labs-backpack']").click()
    expect(page.locator("[data-test='shopping-cart-badge']")).to_have_text("1")

    # Open the cart and check its contents
    page.locator("[data-test='shopping-cart-link']").click()
    expect(page).to_have_url(re.compile(r".*/cart\.html"))
    expect(page.locator("[data-test='inventory-item-name']")).to_have_text("Sauce Labs Backpack")

What changed:

  • Single quotes inside the selectors ([data-test='username']) avoid the \" escapes and are easier to read. Both forms are valid CSS.
  • Three checkpoints now prove the flow works: the inventory page opened, the cart badge shows 1, and the cart contains the backpack.
  • Comments split the test into readable stages.

And the practice-page recording, cleaned up (tests/test_practice_form.py):

📄 tests/test_practice_form.py

from playwright.sync_api import Page, expect


def test_fill_practice_form(page: Page) -> None:
    page.goto("https://sqatools.in/automation-practice-page/")

    username = page.get_by_role("textbox", name="Enter username")
    username.fill("qa_learner")
    expect(username).to_have_value("qa_learner")

    female = page.get_by_role("radio", name="Female")
    female.check()
    expect(female).to_be_checked()

    python = page.get_by_role("checkbox", name="Python")
    python.check()
    expect(python).to_be_checked()

    country = page.locator("#country")
    country.select_option("india")
    expect(country).to_have_value("india")
  • Storing a locator in a variable (username = ...) avoids repeating it for the action and the assertion.
  • to_have_value, to_be_checked and friends verify that each action really took effect.

Both tests pass:

🖥️ Output

tests/test_cart.py::test_user_can_add_backpack_to_cart[chromium] PASSED
tests/test_practice_form.py::test_fill_practice_form[chromium] PASSED
tests/test_recorded_login.py::test_example[chromium] PASSED

⚙️ Recording with Emulation and Saved Logins

Codegen accepts the same kind of options as a browser context, so you can record exactly the situation you want to test:

⌨️ Terminal

# Record on an emulated phone
playwright codegen --target python-pytest --device "iPhone 13" https://www.saucedemo.com/

# Record with a fixed window size, language and time zone
playwright codegen --viewport-size "1280,720" --lang "en-GB" --timezone "Europe/London" https://www.saucedemo.com/

# Record in dark mode
playwright codegen --color-scheme dark https://www.saucedemo.com/

# Log in once and save the session, then record later flows already logged in
playwright codegen --save-storage auth.json https://www.saucedemo.com/
playwright codegen --load-storage auth.json https://www.saucedemo.com/inventory.html
  • --save-storage auth.json saves cookies and local storage when you close the browser; --load-storage auth.json starts the next session with them, so you skip the login steps.
  • Other useful options: -b firefox or -b webkit to record in another engine, --ignore-https-errors for test servers with self-signed certificates, and --save-har to save all network traffic.

⚠️ Watch out: auth.json contains session cookies, which work like a password. Add it to .gitignore and never commit it.


⏸️ Record from Inside a Test: page.pause()

Sometimes you want to record the middle of a flow, after your test has already logged in or prepared data. Add page.pause() where you want to start, and run the test headed:

def test_record_after_login(page: Page) -> None:
    page.goto("https://www.saucedemo.com/")
    page.locator("[data-test='username']").fill("standard_user")
    page.locator("[data-test='password']").fill("secret_sauce")
    page.locator("[data-test='login-button']").click()

    page.pause()   # opens the Playwright Inspector here

⌨️ Terminal

pytest tests/test_record_after_login.py --headed

The test stops at page.pause() and opens the Inspector. Click Record to record new steps from that point, then copy the generated lines into your test and remove page.pause().


🏋️ 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: Write the command that starts Codegen for the SQA Shop, generates pytest code and saves it to tests/test_recorded.py.

Show answer
playwright codegen --target python-pytest -o tests/test_recorded.py https://sqatools.in/dummy-ecommerce-website/

Exercise 2: Codegen recorded this code. Rewrite it as a clean test with a meaningful assertion.

page.goto("https://sqatools.in/dummy-ecommerce-website/")
page.get_by_test_id("search-input").click()
page.get_by_test_id("search-input").fill("earbuds")
page.get_by_test_id("search-button").click()
page.get_by_test_id("product-name").first.click()
Show answer
from playwright.sync_api import Page, expect


def test_open_first_earbuds(page: Page):
    page.goto("https://sqatools.in/dummy-ecommerce-website/")
    page.get_by_test_id("search-input").fill("earbuds")          # the extra click is not needed
    page.get_by_test_id("search-button").click()
    page.get_by_test_id("product-name").first.click()
    expect(page.get_by_test_id("pdp-title")).to_contain_text("Earbuds")

Exercise 3: Record a session as a phone with a dark colour scheme. Which Codegen options do you use?

Show answer
playwright codegen --device "Pixel 7" --color-scheme dark https://sqatools.in/dummy-ecommerce-website/

🧠 MCQ Quiz: Record Tests with Playwright Codegen

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. What does Codegen produce?
  2. Which target produces pytest-style code?
  3. Which option saves the generated code to a file?
  4. Which locators does Codegen prefer?
  5. What must you usually add to recorded code?
  6. How can you record from the middle of an existing test?
  7. Which toolbar feature lets you click an element to get its locator?
  8. How do you record in an emulated iPhone?
  9. Which Codegen options help when the recording needs a logged-in user?
  10. Why should recorded code be refactored before committing?

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


❓ Frequently Asked Questions

🤔 Should I build my whole suite with Codegen?

No. Use it to learn the API, discover locators and draft tests quickly. Real suites need assertions, reusable page objects and test data, which you will add yourself in later modules.

🤔 Why does Codegen generate page.locator(“#id”) instead of get_by_role?

It chooses the most reliable locator it can find. When an element has no accessible name that is unique on the page, an id or test-id selector is safer. You can always change it.

🤔 Can Codegen record file uploads, new tabs and dialogs?

Yes. It records uploads as set_input_files(), new tabs inside a with page.expect_popup() as page1_info: block, downloads inside with page.expect_download(), and dialogs as page.once("dialog", lambda dialog: dialog.dismiss()). Note that the dialog handler dismisses the dialog (like clicking Cancel); change it to dialog.accept() if your test needs OK. You will learn all of these in Module 4.

🤔 What is the difference between python and python-pytest targets?

python writes a standalone script that launches and closes the browser itself with sync_playwright(). python-pytest writes a test function that receives the page fixture, ready to drop into your tests folder.


🏁 Summary

  • playwright codegen --target python-pytest -o tests/test_x.py URL records a pytest test.
  • Codegen prefers test ids, then roles and names; Pick locator shows the locator for any element.
  • Recordings have no assertions: rename, remove extra clicks, add expect() checks and tidy locators.
  • Use emulation flags, --save-storage/--load-storage and page.pause() to record exactly the flow you need.

That completes Module 1. Test yourself with the Module 1 mock interview, then continue to Module 2, Python essentials for Playwright.

🎬 Watch the Playwright tutorial series on YouTube!

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

Configure Playwright Python Tests: pytest.ini, pyproject.toml and conftest.py

Playwright with TypeScript has a single playwright.config.ts file. In Python, configuration is split between two places that every pytest user knows: a settings file (pytest.ini or pyproject.toml) for default command-line options, and conftest.py for Python code that customises the browser, context and timeouts. In this lesson you will build a complete, realistic configuration step by step and verify each setting with a test.

📖 What You’ll Learn: where pytest looks for configuration, addopts, testpaths and base_url in pytest.ini and pyproject.toml, how addopts combines with command-line options, overriding browser_context_args and browser_type_launch_args in conftest.py, per-test context settings with a marker, and setting default timeouts for actions and assertions.


🗺️ Where Configuration Lives

What you want to configureWhere it goesExample
Default command-line optionspytest.ini or pyproject.toml (addopts)--browser chromium --tracing retain-on-failure
Where tests live, base URLpytest.ini or pyproject.tomltestpaths = tests, base_url = https://...
Browser launch settingsconftest.py fixture browser_type_launch_argsextra Chromium flags
Context settings (viewport, locale, timezone, HTTPS errors)conftest.py fixture browser_context_args{"viewport": {"width": 1440, "height": 900}}
Timeoutsconftest.pyexpect.set_options(timeout=10_000)

pytest finds its settings file by looking in the folder you run it from and then in parent folders. Put the settings file and conftest.py in your project’s root folder, next to the tests folder.


📄 Option 1: pytest.ini

Create pytest.ini in the project root:

📄 pytest.ini

[pytest]
# Look for tests only in the tests folder
testpaths = tests

# Options added to every pytest run
addopts = -v --tracing retain-on-failure --screenshot only-on-failure

# Relative URLs in page.goto() are resolved against this
base_url = https://sqatools.in
  • [pytest] is the required section header.
  • testpaths = tests makes a bare pytest command search only the tests folder, which is faster and avoids collecting stray files.
  • addopts is added in front of whatever you type, so every run now uses verbose output and keeps traces and screenshots of failures.
  • base_url lets tests call page.goto("/automation-practice-page/"). A --base-url on the command line takes priority over this value.
  • Lines starting with # are comments.

📄 Option 2: pyproject.toml

Many Python projects keep all tool settings in pyproject.toml. The same configuration looks like this:

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tracing retain-on-failure --screenshot only-on-failure"
base_url = "https://sqatools.in"
  • The section is [tool.pytest.ini_options], and values follow TOML rules: strings in quotes, lists in square brackets.
  • pytest 9 also accepts a native [tool.pytest] table, where addopts is a list: addopts = ["-v", "--tracing", "retain-on-failure"]. The ini_options form works on every pytest version, so it is the safer choice for shared projects.

⚠️ Watch out: Use only one settings file. If both pytest.ini and a [tool.pytest.ini_options] section exist, pytest.ini wins and the pyproject settings are ignored. The only sign is a short note in the run header: configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!). Check the configfile: line whenever settings seem to have no effect.


⚖️ How addopts Combines with the Command Line

addopts does not replace what you type; it is added before it. For options that take one value, the last one wins, so the command line overrides the file. But --browser can be repeated, so the values add up. To see it, imagine addopts = --browser firefox in pytest.ini and this small test:

def test_which_browser(page, browser_name):
    print("RUN", browser_name)

⌨️ Terminal

pytest -q -s --browser webkit

🖥️ Output

RUN firefox
RUN webkit
2 passed in 2.04s

The test ran in both Firefox (from the file) and WebKit (from the command line). If you want to switch browsers freely from the command line, do not put --browser in addopts; Chromium is already the default.


🐍 conftest.py: Python-Powered Configuration

conftest.py is a special pytest file. Fixtures defined in it are available to every test in its folder and sub-folders without importing anything. pytest-playwright builds its browser, context and page fixtures from a few settings fixtures, and you customise them by redefining those settings fixtures in conftest.py.

Create conftest.py in the project root:

📄 conftest.py

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    """Settings applied to every new browser context (and so every page)."""
    return {
        **browser_context_args,                        # keep the plugin's own settings
        "viewport": {"width": 1440, "height": 900},    # larger desktop window
        "locale": "en-GB",                             # browser language
        "timezone_id": "Europe/London",                # browser time zone
        "ignore_https_errors": True,                   # accept self-signed test certificates
    }


@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
    """Settings used when the browser process is launched."""
    return {
        **browser_type_launch_args,
        "slow_mo": 0,                                  # keep 0 in CI; raise it to watch tests
    }


@pytest.fixture(autouse=True)
def default_timeouts(page: Page):
    """Runs before every test: make actions and navigations time out after 15 s."""
    page.set_default_timeout(15_000)
    page.set_default_navigation_timeout(30_000)


# Web-first assertions (expect) wait 5 s by default; give slow pages 10 s
expect.set_options(timeout=10_000)

Line by line:

  1. **browser_context_args** is a session-scoped fixture provided by pytest-playwright. Your version receives the original as a parameter (also named browser_context_args), and returns a new dictionary that starts with **browser_context_args so the plugin’s own settings (such as the --base-url and --device values) are kept, then adds yours.
  2. The keys are the same as the parameters of browser.new_context(): viewport, locale, timezone_id, ignore_https_errors, user_agent, color_scheme, geolocation, permissions, storage_state, and more.
  3. **scope="session"** must match the plugin’s fixture, because the settings are calculated once for the whole run.
  4. **browser_type_launch_args** works the same way for launch() options such as slow_mo, args (extra browser command-line flags) or downloads_path.
  5. **autouse=True** runs the default_timeouts fixture for every test automatically. It asks for page, so it changes the timeouts of the very page your test receives.
  6. **expect.set_options(timeout=10_000)** changes the default wait for every expect() assertion. Because conftest.py is imported before the tests run, it applies everywhere.

💡 Tip: 15_000 is the same number as 15000. Python ignores the underscores; they just make large numbers easier to read.


✅ Prove the Configuration Works

Create tests/test_config.py:

📄 tests/test_config.py

from playwright.sync_api import Page, expect


def test_context_settings_are_applied(page: Page):
    page.goto("/automation-practice-page/")    # relative URL thanks to base_url

    assert page.viewport_size == {"width": 1440, "height": 900}
    assert page.evaluate("navigator.language") == "en-GB"
    assert page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone") == "Europe/London"


def test_base_url_is_used(page: Page):
    page.goto("/automation-practice-page/")
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")

Run pytest with no arguments:

⌨️ Terminal

pytest

🖥️ Output

configfile: pytest.ini
testpaths: tests
plugins: playwright-0.10.0
collecting ... collected 3 items

tests/test_config.py::test_context_settings_are_applied[chromium] PASSED [ 33%]
tests/test_config.py::test_base_url_is_used[chromium] PASSED             [ 66%]
tests/test_markers.py::test_dark_mode_for_one_test[chromium] PASSED      [100%]
  • configfile: pytest.ini and testpaths: tests confirm which settings file pytest used.
  • The -v style output appears without typing -v, because it is in addopts.
  • The plugins line on your machine may list different plugins; that is fine.

The same tests also pass in Firefox, which shows the settings are browser-independent:

⌨️ Terminal

pytest --browser firefox

🎯 Different Settings for One Test

Sometimes one test needs something special, such as dark mode or a different language. pytest-playwright provides a marker for that. Create tests/test_markers.py:

📄 tests/test_markers.py

import pytest
from playwright.sync_api import Page


@pytest.mark.browser_context_args(color_scheme="dark", locale="fr-FR")
def test_dark_mode_for_one_test(page: Page):
    page.goto("/automation-practice-page/")

    assert page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches") is True
    assert page.evaluate("navigator.language") == "fr-FR"
  • @pytest.mark.browser_context_args(...) adds or overrides context settings for this test only.
  • Settings from conftest.py that the marker does not mention (here the 1440×900 viewport) still apply.
  • matchMedia(...) is a browser API; the test asks the page whether it is in dark mode.

🗂️ The Project Structure

🖥️ Output

playwright-python-demo/
├── .venv/
├── conftest.py          # fixtures: context args, launch args, timeouts
├── pytest.ini           # defaults: testpaths, addopts, base_url
├── requirements.txt
└── tests/
    ├── test_config.py
    └── test_markers.py

🔁 TypeScript Config vs Python Config

If you know Playwright with TypeScript, this table maps the familiar playwright.config.ts settings to Python:

playwright.config.tsPython equivalent
testDir: './tests'testpaths = tests
use: { baseURL }base_url in pytest.ini, or --base-url
use: { viewport, locale, timezoneId }browser_context_args fixture in conftest.py
use: { trace: 'retain-on-failure' }--tracing retain-on-failure in addopts
expect: { timeout: 10000 }expect.set_options(timeout=10_000)
use: { actionTimeout }page.set_default_timeout() in an autouse fixture
projects: [...]--browser (repeatable) or --device
retries: 2pytest-rerunfailures plugin: --reruns 2
workers: 4pytest-xdist plugin: -n 4

🏋️ 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: Write a pytest.ini that only collects tests from tests/, uses https://sqatools.in as base URL and always keeps screenshots of failures.

Show answer
[pytest]
testpaths = tests
addopts = --base-url https://sqatools.in --screenshot only-on-failure

Exercise 2: Write a conftest.py that makes every test use a 1366×768 viewport and the en-IN locale, keeping pytest-playwright’s other defaults.

Show answer
import pytest


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {**browser_context_args, "viewport": {"width": 1366, "height": 768}, "locale": "en-IN"}

Exercise 3: Give one test a dark colour scheme without changing the others.

Show answer
import pytest


@pytest.mark.browser_context_args(color_scheme="dark")
def test_dark_mode(page):
    page.goto("/automation-practice-page/")
    assert page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")

🧠 MCQ Quiz: Configure Tests: pytest.ini, pyproject.toml, conftest.py

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 files can hold pytest configuration?
  2. In pyproject.toml, which table holds pytest settings?
  3. What does addopts do?
  4. What does testpaths control?
  5. Which fixture should you override to set viewport or locale for all tests?
  6. Which fixture controls browser launch options such as slow_mo?
  7. Why write {**browser_context_args, ...} in an override?
  8. Which marker changes context settings for a single test?
  9. How do you change the default timeout of every expect assertion?
  10. If both pytest.ini and pyproject.toml exist, which is used?

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


❓ Frequently Asked Questions

🤔 Can I have more than one conftest.py?

Yes. A conftest.py in a sub-folder adds or overrides fixtures for the tests in that folder only. The root conftest.py applies to everything. You will use this in Sharing Fixtures with conftest.py.

🤔 Why does my browser_context_args override seem to do nothing?

The most common causes are a missing scope="session", forgetting to return the dictionary, or a key misspelled (for example timezone instead of timezone_id). Run a test that prints page.viewport_size or navigator.language to confirm.

🤔 Where do I set the browser headless mode in config?

Headless is the default. Add --headed to addopts if you want windows on your own machine, but do not commit that, because CI servers have no screen.

🤔 Should I put secrets like passwords in pytest.ini?

No. Keep secrets in environment variables or a .env file that is not committed. You will learn this in Environment Variables and .env Files.


🏁 Summary

  • pytest.ini or pyproject.toml holds testpaths, addopts and base_url; use only one settings file.
  • addopts is added before command-line options, and repeatable options like --browser add up.
  • Override browser_context_args and browser_type_launch_args in conftest.py (session scope, keep the original with **).
  • Use an autouse fixture for action timeouts, expect.set_options() for assertion timeouts, and the browser_context_args marker for one-off settings.

Next, you will let Playwright write tests for you with Codegen, and learn how to turn recorded code into clean pytest tests.

🎬 Watch the Playwright tutorial series on YouTube!

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

Run Playwright Python Tests: pytest and pytest-playwright CLI Options Explained

You can change how your whole test suite runs without touching a single line of test code. pytest-playwright adds options to the pytest command for picking browsers, watching tests run, emulating phones and capturing screenshots, videos and traces when something fails. In this lesson you will try each option on a small test file and see exactly what it produces.

📖 What You’ll Learn: running tests in Chromium, Firefox and WebKit, using installed Chrome or Edge, headed mode and slow motion, device emulation, capturing screenshots, videos and traces only on failure, the test-results folder, –base-url, and the core pytest flags for selecting and reporting tests.


🧪 The Test File for This Lesson

Create tests/test_cli.py. It has one passing test, one test that fails on purpose (so you can see failure artifacts), one test that prints the viewport size, and one test that uses a relative URL:

📄 tests/test_cli.py

from playwright.sync_api import Page, expect


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


def test_broken_heading(page: Page):
    # Fails on purpose: the real heading text is "Text Fields"
    page.goto("https://sqatools.in/automation-practice-page/")
    heading = page.get_by_role("heading", name="Text Fields")
    expect(heading).to_have_text("Text Boxes", timeout=1000)


def test_viewport(page: Page, browser_name: str):
    size = page.viewport_size
    is_mobile = "Mobile" in page.evaluate("navigator.userAgent")
    print(f"\n{browser_name}: viewport {size['width']}x{size['height']}, mobile user agent: {is_mobile}")


def test_relative_url(page: Page):
    # Works only when a base URL is set (see --base-url below)
    page.goto("/automation-practice-page/")
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")
  • browser_name is another pytest-playwright fixture: a string such as "chromium". Asking for it is as simple as adding a parameter.
  • page.viewport_size returns a dictionary like {'width': 1280, 'height': 720}.
  • timeout=1000 makes the failing assertion give up after 1 second instead of the default 5, so the demo is quick.

🌐 Choose the Browser: –browser and –browser-channel

Without options, tests run in Chromium. Pick another engine with --browser:

⌨️ Terminal

pytest --browser firefox
pytest --browser webkit

Repeat the option to run every test in several browsers in one go:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit -k title

🖥️ Output

...                                                                      [100%]
3 passed, 9 deselected in 9.37s

The single test_practice_title test ran three times, once per browser (that is what the three dots mean). With -v you would see the suffixes [chromium], [firefox] and [webkit].

To run Google Chrome or Microsoft Edge as installed on your machine (instead of Playwright’s own Chromium build), use a channel:

⌨️ Terminal

pytest --browser-channel chrome
pytest --browser-channel msedge

💡 Tip: Testing in branded Chrome or Edge is useful when you must match exactly what your users run. For everyday runs, Playwright’s bundled Chromium is faster to set up and identical across machines.


👀 Watch Tests Run: –headed and –slowmo

⌨️ Terminal

pytest --headed
pytest --headed --slowmo 1000
  • --headed opens visible browser windows. By default tests are headless.
  • --slowmo 1000 waits 1000 milliseconds after every Playwright action, so you can follow each step. Never leave it on in CI: it makes every test much slower.

📱 Emulate a Device: –device

--device applies one of Playwright’s built-in device profiles (screen size, user agent, touch support, pixel ratio) to every test:

⌨️ Terminal

pytest -s --device "iPhone 13" -k viewport

🖥️ Output

chromium: viewport 390x664, mobile user agent: True
1 passed, 3 deselected in 0.49s

Without the option, the same test prints the default desktop viewport:

⌨️ Terminal

pytest -s -k viewport

🖥️ Output

chromium: viewport 1280x720, mobile user agent: False
  • Device names must match Playwright’s list exactly, including capitals and spaces, so put them in quotes. Popular ones include "iPhone 13", "Pixel 7" and "iPad Pro 11".
  • The browser engine is still chosen by --browser (Chromium by default). For the most realistic iPhone emulation, combine --browser webkit --device "iPhone 13".
  • -s turns off pytest’s output capturing so that print() output appears in the terminal.

You will go deeper in Mobile Device Emulation.


📸 Capture Evidence: –screenshot, –video and –tracing

When a test fails in CI, you need evidence. These options record it automatically:

OptionValuesWhat you get
--screenshoton, off, only-on-failureA PNG taken at the end of each test
--full-page-screenshotflagMake those screenshots capture the full scrolling page (use with --screenshot)
--videoon, off, retain-on-failureA .webm recording of each test
--tracingon, off, retain-on-failureA trace.zip you can replay step by step in the Trace Viewer
--outputfolder pathWhere all of these go (default test-results)

The most useful combination keeps evidence only for failed tests:

⌨️ Terminal

pytest -k "not relative" --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure

🖥️ Output

FAILED tests/test_cli.py::test_broken_heading[chromium] - AssertionError: Loc...
1 failed, 2 passed, 1 deselected in 6.12s

(-k "not relative" skips the relative-URL test for now, because it needs the --base-url option shown later in this lesson.)

The test-results folder now holds one sub-folder, for the failed test only:

🖥️ Output

test-results/
└── tests-test-cli-py-test-broken-heading-chromium/
    ├── test-failed-1.png
    ├── trace.zip
    └── video.webm
  • The folder name is built from the file name, the test name and the browser, so failures in different browsers never overwrite each other.
  • Passing tests left nothing behind, which keeps CI artifacts small.
  • Open the trace with playwright show-trace test-results/tests-test-cli-py-test-broken-heading-chromium/trace.zip. You will learn the Trace Viewer in Module 11.

📝 Note: pytest-playwright clears the output folder at the start of each run, so old artifacts never get mixed with new ones.


🔗 Shorter URLs: –base-url

Typing the full URL in every test is repetitive, and it makes it hard to run the same tests against a staging server. Set a base URL once and use relative paths:

⌨️ Terminal

pytest --base-url https://sqatools.in -k relative

🖥️ Output

.                                                                        [100%]
1 passed, 3 deselected in 1.29s

page.goto("/automation-practice-page/") was resolved against the base URL. In pytest-playwright 0.10 the --base-url option works out of the box. You can also set it with the PYTEST_BASE_URL environment variable or a base_url entry in pytest.ini, which you will do in the next lesson.


🎯 Core pytest Options You Will Use Every Day

These come from pytest itself and combine freely with the Playwright options:

OptionMeaning
-v / -qMore / less output
-k "expression"Run tests whose names match, e.g. -k "login and not locked"
-m markerRun tests with a marker, e.g. -m smoke (Module 3)
-xStop after the first failure
--maxfail=3Stop after three failures
-sShow print() output
--lfRe-run only the tests that failed last time
--collect-onlyList the tests without running them
--durations=5Show the five slowest tests

For example, --collect-only -q lists every test with its browser suffix:

⌨️ Terminal

pytest --collect-only -q

🖥️ Output

tests/test_cli.py::test_practice_title[chromium]
tests/test_cli.py::test_broken_heading[chromium]
tests/test_cli.py::test_viewport[chromium]
tests/test_cli.py::test_relative_url[chromium]

4 tests collected in 0.00s

🧾 Quick Reference

⌨️ Terminal

# All browsers, verbose
pytest --browser chromium --browser firefox --browser webkit -v

# Debug one test visually
pytest tests/test_login.py::test_valid_login_shows_products --headed --slowmo 500

# CI-style run with evidence on failure
pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure

# Same tests against another environment
pytest --base-url https://staging.example.com

To see every option on your machine, run pytest --help and look for the Playwright section.


🏋️ 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: Write one command that runs all tests in Firefox and WebKit, headed, slowed down by 200 ms.

Show answer
pytest --browser firefox --browser webkit --headed --slowmo 200

Exercise 2: Write the command that keeps a screenshot, a video and a trace only for failed tests and stores them in a folder called artifacts.

Show answer
pytest --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure --output artifacts

Exercise 3: Your tests call page.goto("/automation-practice-page/"). Which option makes this work, and what is the full URL opened?

Show answer

--base-url https://sqatools.in (or base_url in the config). The test then opens https://sqatools.in/automation-practice-page/.


🧠 MCQ Quiz: pytest-playwright CLI Options

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 option runs tests in Firefox?
  2. How do you run tests in the installed Google Chrome?
  3. What does --headed do?
  4. What does --device "iPhone 15" change?
  5. Where are screenshots, videos and traces saved by default?
  6. What does --tracing retain-on-failure do?
  7. Which pytest option stops at the first failure?
  8. Which option reruns only the tests that failed last time?
  9. What does --slowmo 500 do?
  10. How do you run the same tests in three browsers in one command?

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


❓ Frequently Asked Questions

🤔 How do I avoid typing the same options every time?

Put them in the addopts setting of pytest.ini or pyproject.toml. That is the first thing you will do in the next lesson.

🤔 Can I run tests in parallel?

Yes, with the pytest-xdist plugin (pytest -n auto). It is covered in Parallel Execution with pytest-xdist.

🤔 Do these options affect browsers I create myself?

No. They configure the browser, context and page fixtures from pytest-playwright. A browser you launch yourself with sync_playwright() inside a test is not affected.

🤔 Is there a –retries option?

Not in pytest-playwright. Retries come from the pytest-rerunfailures plugin (pytest --reruns 2), covered in Module 6.


🏁 Summary

  • --browser (repeatable) and --browser-channel choose where tests run; --headed and --slowmo let you watch.
  • --device emulates phones and tablets; -s shows printed output.
  • --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure keeps evidence for failed tests in test-results.
  • --base-url lets tests use relative URLs; pytest’s own flags (-k, -x, -v, --lf) select and report tests.

Next, you will move these options into configuration files and learn how conftest.py customises the browser and context for the whole suite.

🎬 Watch the Playwright tutorial series on YouTube!

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

Write and Run Your First pytest Playwright Test in Python

Now you will write real tests. With pytest and the pytest-playwright plugin, you never launch or close a browser yourself: you ask for a page, use it, and pytest cleans up. In this lesson you will understand every line of a Playwright test, automate a login page, add negative tests, run them in different ways, and learn to read a failure message.

📖 What You’ll Learn: test anatomy (test function, page fixture, expect), pytest discovery rules, writing a login test with Arrange-Act-Assert, negative tests, why every test gets a fresh page, running tests from the CLI, and reading a failing test’s output.


🧱 Anatomy of a Playwright Test

Create a tests folder in your project and add tests/test_title.py:

📄 tests/test_title.py

from playwright.sync_api import Page, expect                      # 1. imports


def test_practice_page_has_title(page: Page):                    # 2. a test function
    page.goto("https://sqatools.in/automation-practice-page/")   # 3. an action
    expect(page).to_have_title("Automation Practice Page - SQA Tools")   # 4. an assertion
  1. Imports. Page is the type of the page object (used for editor auto-complete) and expect creates Playwright assertions.
  2. A test function. pytest runs any function whose name starts with test_. The parameter page is a fixture: pytest-playwright sees the name, creates a fresh page in a new browser context, passes it in, and closes it after the test. The : Page part is a type hint; it does not change behaviour, but it gives you auto-complete in VS Code.
  3. An action. page.goto() opens the URL.
  4. An assertion. expect(page).to_have_title(...) checks the title. If it does not match yet, it retries for up to 5 seconds before failing. This is called a *web-first assertion*.

Run it:

⌨️ Terminal

pytest tests/test_title.py

🔍 How pytest Finds Your Tests

When you run pytest, it searches the current folder and its subfolders. By default it collects:

  • files named test_*.py or *_test.py,
  • functions named test_* in those files,
  • methods named test_* inside classes named Test* (the class must not have an __init__ method).

So tests/test_login.py with def test_valid_login(page) is found automatically, while tests/login.py or def check_login(page) would be silently ignored. You will learn how to change these rules in pytest Configuration.

⚠️ Watch out: A test file named test_something.py that is never collected is almost always caused by a typo in the file or function name. Run pytest --collect-only to list what pytest found without running it.


✍️ A Real Test: Login

Next, automate the login page of Sauce Demo (https://www.saucedemo.com), a free practice shop that accepts the username standard_user and password secret_sauce. Create tests/test_login.py:

📄 tests/test_login.py

import re

from playwright.sync_api import Page, expect


def test_valid_login_shows_products(page: Page):
    # Arrange: open the login page
    page.goto("https://www.saucedemo.com/")

    # Act: fill the form and submit
    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()

    # Assert: we land on the products page
    expect(page).to_have_url(re.compile(r".*/inventory\.html"))
    expect(page.locator(".title")).to_have_text("Products")


def test_wrong_password_shows_error(page: Page):
    page.goto("https://www.saucedemo.com/")

    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("wrong_password")
    page.get_by_role("button", name="Login").click()

    error = page.locator("[data-test='error']")
    expect(error).to_be_visible()
    expect(error).to_contain_text("Username and password do not match")


def test_locked_out_user_cannot_log_in(page: Page):
    page.goto("https://www.saucedemo.com/")

    page.get_by_placeholder("Username").fill("locked_out_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()

    expect(page.locator("[data-test='error']")).to_contain_text("locked out")
    expect(page).to_have_url("https://www.saucedemo.com/")

What the new pieces do:

  • Arrange, Act, Assert. The comments split the first test into setting up, doing the user action, and checking the result. Keeping this shape makes tests easy to read and review.
  • get_by_placeholder("Username") finds an input by its placeholder text; get_by_role("button", name="Login") finds the button by its role and visible name, the way a user sees it.
  • to_have_url(re.compile(...)) accepts either an exact string or a regular expression. The pattern .*/inventory\.html means “any URL ending in /inventory.html”; the backslash makes the dot literal.
  • page.locator(".title") uses a CSS selector. to_have_text("Products") checks the element’s full text, while to_contain_text() checks for a substring.
  • "[data-test='error']" is a CSS attribute selector. Many apps add data-test or data-testid attributes for exactly this purpose.
  • The second and third tests are negative tests: they prove the app rejects bad input. A good suite always tests both the happy path and the failure paths.

Run the file with -v (verbose) to see each test by name:

⌨️ Terminal

pytest tests/test_login.py -v

🖥️ Output

tests/test_login.py::test_valid_login_shows_products[chromium] PASSED    [ 33%]
tests/test_login.py::test_wrong_password_shows_error[chromium] PASSED    [ 66%]
tests/test_login.py::test_locked_out_user_cannot_log_in[chromium] PASSED [100%]

The [chromium] suffix is added by pytest-playwright: it shows which browser ran the test. Chromium is the default, and you will run the same tests in Firefox and WebKit in the next lesson.


🔒 Every Test Gets a Fresh Page

The tests above never log out, yet the second test starts on the login page as a stranger. That is because each test receives a new browser context: new cookies, new storage, nothing left over from the previous test. This file proves it (tests/test_isolation.py):

📄 tests/test_isolation.py

from playwright.sync_api import Page


def test_first_saves_a_value(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    page.evaluate("localStorage.setItem('step', 'done')")
    assert page.evaluate("localStorage.getItem('step')") == "done"


def test_second_starts_clean(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    assert page.evaluate("localStorage.getItem('step')") is None
  • The first test stores a value in the page’s localStorage and checks it with a plain Python assert.
  • The second test opens the same site in its own fresh context and finds nothing there.

💡 Tip: Use plain assert for Python values you already have (numbers, strings, lists). Use expect(...) for anything on the page, because it waits and retries while the page catches up.


💥 Reading a Failure

Tests fail, and reading the failure quickly is a core skill. Here is a test with a deliberate mistake (tests/test_failing.py):

📄 tests/test_failing.py

from playwright.sync_api import Page, expect


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

The expected title says “Practise” instead of “Practice”. Run it:

⌨️ Terminal

pytest tests/test_failing.py

🖥️ Output

================================== FAILURES ===================================
__________________________ test_title_typo[chromium] __________________________

page = <Page url='https://sqatools.in/automation-practice-page/'>

    def test_title_typo(page: Page):
        page.goto("https://sqatools.in/automation-practice-page/")
>       expect(page).to_have_title("Automation Practise Page - SQA Tools")
E       AssertionError: Page title expected to be 'Automation Practise Page - SQA Tools'
E       Actual value: Automation Practice Page - SQA Tools
E       Call log:
E         - Expect "to_have_title" with timeout 5000ms
E           13 × locator resolved to <html lang="en-US" prefix="og: https://ogp.me/ns#">…</html>
E              - unexpected value "Automation Practice Page - SQA Tools"
E
E       Aria snapshot:
E       - link "Skip to content":
E         - /url: "#content"
E       - banner "Site":
E       ...  (the rest of the page structure, cut here)

tests\test_failing.py:6: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_failing.py::test_title_typo[chromium] - AssertionError: Pag...
============================== 1 failed in 7.08s ==============================

How to read it, top to bottom:

  1. **The > marker** points at the line that failed, inside a copy of your test code.
  2. What was expected and what the page actually had (Actual value). Comparing these two lines usually reveals the bug immediately.
  3. The call log shows that Playwright kept checking for 5 seconds (the default assertion timeout) and saw the same wrong value each time, so this is not a timing problem.
  4. The aria snapshot (added by recent Playwright versions) is a text outline of the page at the moment of failure: headings, links, buttons, fields. It helps you see what was really on screen, especially in CI where you cannot watch the browser.
  5. The file and line number (test_failing.py:6) and the short summary list every failed test with its browser.

📝 Note: The exact retry count in the call log (here 13 ×) and the run time vary from run to run. That is normal.


▶️ Running Tests: The Essentials

CommandWhat it does
pytestRun every test pytest can find
pytest tests/test_login.pyRun one file
pytest tests/test_login.py::test_wrong_password_shows_errorRun one test
pytest -k "login and not locked"Run tests whose names match the expression
pytest -vShow each test name and result
pytest -xStop at the first failure
pytest --headedShow the browser window

The next lesson covers every Playwright-specific option, such as --browser, --slowmo, --screenshot and --tracing.


🏋️ 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: Write a pytest test that opens the SQA Shop login page, logs in as testuser / Test@123 and checks that the header shows “Hi, Test”. Use Arrange-Act-Assert comments.

Show answer
from playwright.sync_api import Page, expect


def test_login(page: Page):
    # Arrange
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    # Act
    page.get_by_test_id("login-username").fill("testuser")
    page.get_by_test_id("login-password").fill("Test@123")
    page.get_by_test_id("login-button").click()
    # Assert
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")

Exercise 2: Write a negative test for the same page: an empty username and password must show “Username and password are required.”

Show answer
def test_empty_login(page: Page):
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-button").click()
    expect(page.get_by_test_id("login-error")).to_have_text("Username and password are required.")

Exercise 3: Your file is called login_checks.py and contains def check_login(page): .... pytest says “no tests ran”. Why, and what are two ways to fix it?

Show answer

pytest only collects files named test_*.py or *_test.py and functions named test_*. Rename the file to test_login.py and the function to test_login, or change python_files/python_functions in the pytest configuration (renaming is the normal choice).


🧠 MCQ Quiz: Write and Run Your First pytest Playwright Test

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 fixture gives a test a ready browser page?
  2. Which function names does pytest collect as tests by default?
  3. What does expect(locator).to_have_text("...") do?
  4. Does each test get a new page?
  5. What is Arrange-Act-Assert?
  6. Which command runs tests verbosely?
  7. How do you run one test by name?
  8. What does the type hint page: Page do?
  9. Where does the “Call log” in a failed expect come from?
  10. Why write negative tests?

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


❓ Frequently Asked Questions

🤔 Why do I not need to launch or close the browser?

The page fixture from pytest-playwright does it. It reuses one browser for the whole run, creates a new context and page for each test, and closes them afterwards, even when the test fails.

🤔 Can I put tests in a class?

Yes. Name the class Test..., do not give it an __init__, and add page as a parameter to each method: def test_login(self, page: Page):. Classes are useful for grouping related tests.

🤔 Why use expect instead of assert?

expect waits and retries until the condition is true or the timeout (5 seconds by default) is reached. A plain assert page.title() == "..." checks only once, so it can fail if the page is still loading.

🤔 Why does the test name end with [chromium]?

pytest-playwright parametrizes tests by browser. If you run with --browser firefox --browser webkit, each test runs once per browser and the suffix shows which run you are looking at.


🏁 Summary

  • A test is a test_ function in a test_*.py file that asks for the page fixture.
  • expect() assertions wait and retry; use plain assert only for values you already hold.
  • Structure tests as Arrange, Act, Assert, and always include negative tests.
  • Each test gets a new context and page, so tests never share state.
  • Failures show expected vs actual values, a call log and the failing line.

Next, you will learn every pytest and pytest-playwright command-line option for running tests in different browsers, headed mode, slow motion and more.

🎬 Watch the Playwright tutorial series on YouTube!

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

Your First Playwright Python Script with sync_playwright (Browser, Context and Page)

Before pytest takes over the browser for you, it is worth writing one complete Playwright script by hand. You will see exactly what happens when a test starts: Playwright launches a browser, creates an isolated context, opens a page, performs actions and closes everything down. Once you understand these four objects, every fixture and error message later in the course will make sense.

📖 What You’ll Learn: the Playwright object hierarchy (Playwright, Browser, BrowserContext, Page), launch options like headless and slow_mo, interacting with a real form, reading text and attributes, taking screenshots, proving that contexts are isolated, and closing resources safely with with and try/finally.


🧱 The Four Objects You Always Use

Every Playwright program, including every pytest test you will write, uses the same chain of objects:

ObjectCreated byWhat it represents
Playwrightsync_playwright()The running Playwright driver. Gives you chromium, firefox, webkit and devices.
Browserp.chromium.launch()One browser process (expensive to start, so reuse it).
BrowserContextbrowser.new_context()An isolated, incognito-like session with its own cookies, storage and cache. Cheap to create.
Pagecontext.new_page()One tab inside a context. Almost all actions happen here.

Think of the browser as a building, each context as a separate flat with its own key, and each page as a room in a flat. Two contexts never share cookies or logins, which is why Playwright tests do not leak state into each other.


✍️ A Complete First Script

This script opens the SQA Tools Automation Practice Page, fills in some fields, reads values back and saves a screenshot. Save it as first_script.py:

📄 first_script.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    # 1. Launch a browser and create an isolated context with one page
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()

    # 2. Open the practice page
    page.goto("https://sqatools.in/automation-practice-page/")
    print("Page title:", page.title())

    # 3. Type into text fields, located by their placeholder text
    page.get_by_placeholder("Enter username").fill("qa_learner")
    page.get_by_placeholder("Enter password").fill("Secret@123")

    # 4. Choose a radio button, tick a checkbox and pick a dropdown option
    page.get_by_role("radio", name="Female").check()
    page.get_by_role("checkbox", name="Python").check()
    page.locator("select").first.select_option("India")

    # 5. Read the values back from the page
    print("Username field:", page.get_by_placeholder("Enter username").input_value())
    print("Python checked:", page.get_by_role("checkbox", name="Python").is_checked())
    print("Second table row:", page.get_by_role("row").nth(2).inner_text())

    # 6. Save a screenshot of the visible part of the page
    page.screenshot(path="practice-page.png")

    # 7. Close everything
    context.close()
    browser.close()

Run it:

⌨️ Terminal

python first_script.py

🖥️ Output

Page title: Automation Practice Page - SQA Tools
Username field: qa_learner
Python checked: True
Second table row: 2	Rahul	Tester

A file named practice-page.png appears next to your script.

What each part does

  1. Launch and open. launch() starts the browser, new_context() creates a clean session, and new_page() opens a tab in it.
  2. **page.goto(url)** navigates and waits for the page’s load event before the next line runs.
  3. **get_by_placeholder("Enter username") creates a locator**: a description of how to find an element. Nothing is searched yet. fill() then finds the input, waits until it is editable, clears it and types the text.
  4. **get_by_role("radio", name="Female")** finds the element the way a screen reader would: by its role (radio) and accessible name (Female). check() ticks radios and checkboxes. select_option("India") picks the option whose value or label is India from the first <select> on the page.
  5. Reading values. input_value() returns what is typed in a field, is_checked() returns True or False, and inner_text() returns the visible text. nth(2) picks the third match (counting starts at 0, and row 0 is the header row). The cells in the printed row are separated by tab characters.
  6. **page.screenshot(path=...)** saves a PNG. Add full_page=True to capture the whole scrolling page.
  7. Closing. Closing the context closes its pages; closing the browser ends the process. Leaving the with block then stops the Playwright driver.

💡 Tip: Notice there is no time.sleep() anywhere. Every action waits automatically until its element is ready. This auto-waiting is the main reason Playwright tests are stable.


👀 Watch the Browser: headless and slow_mo

By default the browser is headless: it runs without a window, which is faster and works on servers. While learning, it helps to watch. Save this as launch_options.py:

📄 launch_options.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=False,   # show the browser window
        slow_mo=500,      # wait 500 ms after each Playwright action
    )
    page = browser.new_page()

    page.goto("https://sqatools.in/automation-practice-page/")
    page.get_by_role("button", name="Hover Over Me").hover()
    print("Hovered on Chromium version", browser.version)

    browser.close()
  • headless=False opens a real window so you can follow along.
  • slow_mo=500 adds a 500 millisecond pause after every action. Use it only for watching or demos, never in real test suites.
  • browser.new_page() is a shortcut that creates a context and a page in one call. It is handy in quick scripts; when you need several pages in the same session, create the context yourself.
  • browser.version returns the browser’s version string.

🖥️ Output

Hovered on Chromium version 156.0.8078.4

To try another engine, change one word: p.firefox.launch(...) or p.webkit.launch(...). The rest of the script stays the same.


🔒 Contexts Are Isolated

This is one of Playwright’s most useful ideas. Two contexts in the same browser behave like two different people on two different computers. Save this as contexts.py:

📄 contexts.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch()

    # Two independent sessions in ONE browser process
    alice = browser.new_context()
    bob = browser.new_context()

    alice_page = alice.new_page()
    bob_page = bob.new_page()

    alice_page.goto("https://sqatools.in/automation-practice-page/")
    bob_page.goto("https://sqatools.in/automation-practice-page/")

    # Alice stores a value in her browser's localStorage
    alice_page.evaluate("localStorage.setItem('user', 'alice')")

    # Bob cannot see it: each context has its own storage
    print("Alice sees:", alice_page.evaluate("localStorage.getItem('user')"))
    print("Bob sees:  ", bob_page.evaluate("localStorage.getItem('user')"))

    print("Contexts open:", len(browser.contexts))
    browser.close()

🖥️ Output

Alice sees: alice
Bob sees:   None
Contexts open: 2
  • page.evaluate("...") runs JavaScript inside the page and returns the result to Python. JavaScript null arrives in Python as None.
  • Bob’s context has no idea what Alice stored, even though both pages are in the same browser.

This is exactly what pytest-playwright does for you: one browser for the whole test session, and a brand-new context and page for every test. Tests start fast, and no cookies or logins leak from one test into the next.


🧹 Closing Safely When Something Fails

If a line throws an error, the code after it never runs. The with sync_playwright() block already guarantees that the driver stops. To make sure the browser itself is closed too, wrap your steps in try/finally. Save this as try_finally.py:

📄 try_finally.py

from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError


with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    try:
        page.goto("https://sqatools.in/automation-practice-page/")

        # This button does not exist, so the click times out after 2 seconds
        page.get_by_role("button", name="Does Not Exist").click(timeout=2000)

    except PlaywrightTimeoutError as error:
        print("Step failed:", error.message.splitlines()[0])

    finally:
        browser.close()     # always runs, even after an error
        print("Browser closed")

🖥️ Output

Step failed: Locator.click: Timeout 2000ms exceeded.
Browser closed
  • TimeoutError from playwright.sync_api is Playwright’s own timeout error. Importing it with an alias avoids confusing it with Python’s built-in TimeoutError.
  • timeout=2000 overrides the default action timeout of 30 seconds for this one click.
  • error.message holds the full message; the first line names the action and the timeout. The lines after it (the call log) show what Playwright was waiting for.
  • The finally block always runs, so the browser never stays open.

📝 Note: You will rarely write try/finally around tests yourself. pytest fixtures handle cleanup automatically, even when a test fails. You will see this in the next lesson.


🏋️ 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: Write a script with sync_playwright that opens the SQA Tools automation practice page in headed mode with slow_mo=300, prints the page title and closes the browser.

Show answer
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=300)
    page = browser.new_page()
    page.goto("https://sqatools.in/automation-practice-page/")
    print(page.title())
    browser.close()

Exercise 2: Show in code that two browser contexts are isolated: set a localStorage value in one and read it in the other.

Show answer
with sync_playwright() as p:
    browser = p.chromium.launch()
    a, b = browser.new_context().new_page(), browser.new_context().new_page()
    for page in (a, b):
        page.goto("https://sqatools.in/automation-practice-page/")
    a.evaluate("localStorage.setItem('k', 'from A')")
    print(b.evaluate("localStorage.getItem('k')"))   # None: contexts do not share storage
    browser.close()

Exercise 3: Wrap a script so the browser is always closed, even when a step fails, without using with.

Show answer
p = sync_playwright().start()
browser = p.chromium.launch()
try:
    page = browser.new_page()
    page.goto("https://sqatools.in/automation-practice-page/")
    page.locator("#username").fill("demo")
finally:
    browser.close()
    p.stop()

🧠 MCQ Quiz: Your First Playwright Script with sync_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. What is the order of objects from top to bottom?
  2. What does headless=False do?
  3. What does slow_mo=500 do?
  4. Which method opens a URL?
  5. What does a BrowserContext represent?
  6. How do you read the value attribute of an input?
  7. Which call takes a screenshot of the whole page?
  8. What does with sync_playwright() as p: guarantee?
  9. Why is browser.close() in a finally block useful?
  10. Is page.title() a property or a method?

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


❓ Frequently Asked Questions

🤔 What is the difference between browser.new_page() and context.new_page()?

browser.new_page() creates a new context and a page in it in one step, and closing that page also closes its context. context.new_page() adds a page to an existing context, so several pages can share the same cookies and login.

🤔 Why does my script finish but the browser window closes immediately?

The script reached browser.close(). To pause and look around, add page.pause() (it opens the Playwright Inspector) or run with slow_mo. You will learn debugging in Module 11.

🤔 Can I connect to a browser that is already open?

Yes, with p.chromium.connect_over_cdp("http://localhost:9222") for Chromium browsers started with remote debugging enabled. Most test suites launch their own browser instead, because it is more reliable.

🤔 What is the default timeout for actions?

30 seconds for actions such as click() and fill(), and 30 seconds for navigation. You can change it per call with timeout= or for a whole context with context.set_default_timeout().


🏁 Summary

  • sync_playwright() gives you a Playwright object; it launches a Browser, which creates BrowserContexts, which open Pages.
  • Locators such as get_by_placeholder() and get_by_role() describe elements; actions such as fill() and check() wait automatically.
  • headless=False and slow_mo help you watch a script; contexts keep sessions fully isolated.
  • Close what you open, or let with blocks and pytest fixtures do it for you.

Next, you will turn this knowledge into your first real pytest test, where the page fixture does all of this setup and cleanup for you.

🎬 Watch the Playwright tutorial series on YouTube!

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

Install Playwright for Python and pytest (Virtual Environment and VS Code Setup)

Before you write a single test you need a clean, repeatable setup. In this lesson you will install Python, create a virtual environment for your test project, install Playwright and pytest with one command, download the browsers, and set up VS Code so it can discover and run your tests.

📖 What You’ll Learn: checking your Python version, creating and activating a virtual environment on Windows, macOS and Linux, installing pytest-playwright, downloading browsers with playwright install, freezing versions in requirements.txt, and running tests from VS Code.


🧰 What You Need

  • Python 3.10 or newer. Playwright 1.64 and pytest-playwright 0.10 both require it.
  • About 1 GB of free disk space for the three browsers.
  • A code editor. This course uses VS Code, which is free.
  • An internet connection for the first install.

You do not need Node.js, Java or a separate WebDriver download.


🐍 Step 1: Install and Check Python

Download Python from python.org/downloads. On Windows, tick “Add python.exe to PATH” on the first installer screen. Then open a new terminal and check the version:

⌨️ Terminal

python --version

On macOS and Linux the command is usually python3:

⌨️ Terminal

python3 --version

You should see Python 3.10 or higher. If you see an older version, or “command not found”, install a current version before continuing.

💡 Tip: In this course, commands use python. If your system only has python3, use that instead everywhere.


📁 Step 2: Create a Project Folder and a Virtual Environment

A virtual environment is a private folder of Python packages for one project. It keeps this project’s Playwright and pytest versions separate from other projects and from the system Python, so upgrading one project never breaks another. You will learn more in Python Virtual Environments and pip.

Create a folder and a virtual environment named .venv inside it:

⌨️ Terminal

mkdir playwright-python-demo
cd playwright-python-demo
python -m venv .venv
  • mkdir creates the project folder and cd moves into it.
  • python -m venv .venv runs Python’s built-in venv module and creates a .venv folder containing a private copy of Python and pip.

Activate the virtual environment

Activation points your terminal’s python and pip at the .venv folder. Use the command for your operating system:

Operating system / shellActivate command
Windows PowerShell.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat
macOS / Linux (bash, zsh)source .venv/bin/activate

When it works, your prompt starts with (.venv). Run deactivate to leave it.

⚠️ Watch out: If PowerShell says that running scripts is disabled, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then activate again. This changes the policy only for your user account.


📦 Step 3: Install pytest-playwright

With the virtual environment active, install the official plugin:

⌨️ Terminal

pip install pytest-playwright

This one command installs three things:

  1. pytest-playwright, the plugin that adds the page fixture and Playwright command-line options.
  2. playwright, the browser automation library (installed automatically as a dependency).
  3. pytest, the test runner (also a dependency).

Check the installed versions:

⌨️ Terminal

playwright --version
pytest --version

🖥️ Output

Version 1.64.1
pytest 9.2.0

Your numbers may be newer. That is fine: everything in this course works with Playwright 1.64 and later.


🌐 Step 4: Download the Browsers

The Python package does not contain the browsers themselves. Download the versions that match your Playwright release:

⌨️ Terminal

playwright install

This downloads Chromium, Firefox and WebKit into a shared cache folder (on Windows %USERPROFILE%\AppData\Local\ms-playwright, on macOS ~/Library/Caches/ms-playwright, on Linux ~/.cache/ms-playwright). Every project on your machine that uses the same Playwright version reuses them.

Useful variations:

  • playwright install chromium downloads only Chromium (faster for a first try).
  • playwright install --with-deps also installs the operating-system libraries the browsers need. Use it on Linux and in CI containers; it may ask for administrator (sudo) permission.
  • playwright install --dry-run shows what would be downloaded and where, without downloading.

📝 Note: Each Playwright version needs its own browser builds. After pip install --upgrade playwright, run playwright install again.


✅ Step 5: Verify the Setup with a Test

Create a folder named tests and a file tests/test_setup.py inside it:

📄 tests/test_setup.py

from playwright.sync_api import Page, expect


def test_setup_works(page: Page):
    # Open the SQA Tools practice page
    page.goto("https://sqatools.in/automation-practice-page/")

    # The test passes if the page title matches
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

Run it from the project folder:

⌨️ Terminal

pytest

🖥️ Output

.                                                                        [100%]
1 passed, 1 warning in 1.98s

The single dot means one test passed. pytest found the test because the file name starts with test_ and the function name starts with test_. You will learn these discovery rules in Lesson 4.

📝 Note: With pytest 9.2 and pytest-playwright 0.10.0 you may also see a PytestRemovedIn10Warning about “Session-scoped fixtures defined as instance methods” for the base_url fixture. It comes from inside the plugin, not from your code, and it does not affect your results.


📌 Step 6: Pin Your Versions in requirements.txt

So that teammates and CI install exactly the same versions, save them to a file:

⌨️ Terminal

pip freeze > requirements.txt

pip freeze lists every installed package with its exact version. On a fresh Windows install in November 2026 the file contained these lines (your versions may be newer, and colorama only appears on Windows):

🖥️ Output

colorama==0.4.6
greenlet==3.5.6
iniconfig==2.3.1
packaging==26.3
playwright==1.64.1
pluggy==1.7.0
pyee==14.0.0
Pygments==2.21.0
pytest==9.2.0
pytest-playwright==0.10.0
python-slugify==9.1.3
text-unidecode==1.3
typing_extensions==4.16.0

Anyone can now recreate your environment with:

⌨️ Terminal

pip install -r requirements.txt
playwright install

💡 Tip: Add .venv/ to your .gitignore file. Commit requirements.txt, never the virtual environment folder itself. See our guide to .gitignore.


💻 Step 7: Set Up VS Code

  1. Open the project folder in VS Code (File > Open Folder).
  2. Install the Python extension by Microsoft from the Extensions view (Ctrl+Shift+X).
  3. Press Ctrl+Shift+P, run Python: Select Interpreter, and choose the interpreter inside .venv.
  4. Open the Testing view (the flask icon), click Configure Python Tests, choose pytest, then choose the tests folder.
  5. Your test appears in the tree. Click the ▶ button next to it to run it, or the debug icon to debug it with breakpoints.

📝 Note: The “Playwright Test for VS Code” extension is built for the Node.js test runner (Playwright Test). For Python projects, run and debug tests through the Python extension’s Testing view as shown above.


🗂️ Your Project So Far

🖥️ Output

playwright-python-demo/
├── .venv/                  # virtual environment (not committed)
├── tests/
│   └── test_setup.py       # your first test
└── requirements.txt        # pinned versions

🏋️ 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: Write the commands to create a virtual environment called .venv, activate it on Windows PowerShell and on macOS/Linux, and install pytest-playwright.

Show answer
python -m venv .venv
.venv\Scripts\Activate.ps1          # Windows PowerShell
source .venv/bin/activate           # macOS / Linux
pip install pytest-playwright

Exercise 2: After pip install pytest-playwright, your first test fails with “Executable doesn’t exist”. What is missing and how do you fix it?

Show answer

The browsers have not been downloaded yet. Run playwright install (or playwright install chromium for one browser); on Linux CI add --with-deps to install the system libraries too.

Exercise 3: Write a requirements.txt that pins the versions used in this course and the command to install from it on another machine.

Show answer
playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pip install -r requirements.txt
playwright install

pip freeze > requirements.txt captures everything installed if you prefer an exact snapshot.


🧠 MCQ Quiz: Install Python, Playwright and pytest

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 command checks your Python version?
  2. Why use a virtual environment?
  3. Which command creates a virtual environment named .venv?
  4. What does pip install pytest-playwright install?
  5. Which command downloads the browsers?
  6. What does --with-deps add to playwright install?
  7. How do you activate a venv in Windows PowerShell?
  8. Why pin versions in requirements.txt?
  9. Which VS Code extension runs and debugs pytest tests?
  10. What is a quick way to verify the whole setup works?

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


❓ Frequently Asked Questions

🤔 pip says “command not found”. What should I do?

Use python -m pip install pytest-playwright. Running pip through python -m always uses the pip that belongs to the active Python.

🤔 Do I have to install all three browsers?

No. If you only test in Chromium, playwright install chromium is enough. You can add the others later.

🤔 Can I use Google Chrome or Microsoft Edge instead of Playwright’s Chromium?

Yes. Install the browser normally (or with playwright install chrome / playwright install msedge) and run tests with pytest --browser-channel chrome. You will learn this in Lesson 5.

🤔 Is pytest-playwright different from playwright?

Yes. playwright is the automation library. pytest-playwright is the plugin that connects it to pytest. Installing the plugin installs the library for you.


🏁 Summary

  • Use Python 3.10+, and give every test project its own virtual environment.
  • pip install pytest-playwright installs the plugin, Playwright and pytest together.
  • playwright install downloads the matching browsers; add --with-deps on Linux and CI.
  • Freeze versions with pip freeze > requirements.txt, and run tests from VS Code’s Testing view.

Next, you will write a complete Playwright script with sync_playwright to understand browsers, contexts and pages before pytest takes over.

🎬 Watch the Playwright tutorial series on YouTube!

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

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.

📖 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.

🏋️ 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: In two or three sentences, explain to a manual tester why Playwright tests are run with pytest and the pytest-playwright plugin instead of plain scripts.

Show answer

pytest finds and runs tests, reports pass/fail, and offers fixtures, parametrization and plugins. pytest-playwright adds ready-made fixtures (page, context, browser) and command-line options (--browser, --headed, --tracing), so each test gets a fresh, isolated browser page without any setup code.

Exercise 2: Name the three browser engines Playwright drives and one real browser each one represents.

Show answer

Chromium (Google Chrome, Microsoft Edge), Firefox (Mozilla Firefox) and WebKit (Apple Safari).

Exercise 3: Rewrite this sync snippet in the async API:

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

The code must run inside an async def function started with asyncio.run(...), and page comes from async_playwright().


🧠 MCQ Quiz: What Is Playwright for Python? Sync API, Async API and pytest

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 company develops Playwright?
  2. Which three browser engines does Playwright support?
  3. Which API is recommended for writing tests with pytest?
  4. What does the pytest-playwright plugin add?
  5. In the async API, what must you write before Playwright calls?
  6. Which statement about Playwright Python vs TypeScript is true?
  7. Which feature helps make Playwright tests less flaky?
  8. Can Playwright for Python run Safari’s engine on Windows?
  9. Which Python package do you install to start writing Playwright tests?
  10. What isolates one Playwright test from another?

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


❓ 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