Playwright MCP and playwright-cli for Python Testers

AI coding agents such as Claude Code and GitHub Copilot can drive a real browser through Playwright, look at the page, and write the test code for you. Two official tools make that possible: the Playwright MCP server and the newer, token-efficient playwright-cli, which ships inside the Playwright Python package. In this lesson you will drive the SQA Shop from the terminal with playwright-cli, read its accessibility snapshots and element refs, turn the Python code it prints into a pytest test, connect the Playwright MCP server to an AI agent with Python code generation, use both safely, and understand what these tools are good at and where you still need to think for yourself.

Advertisement

📖 What You’ll Learn: what MCP is and how Playwright MCP works, the difference between MCP and playwright-cli, running python -m playwright cli, sessions, open, snapshot, find, fill, click and close, element refs and why they expire, the Python code the CLI prints, state-save and Lesson 51, turning a session into a pytest test, the –playwright-debug=cli option of pytest-playwright, configuring Playwright MCP for Claude Code and VS Code with –codegen python, useful MCP options, a prompt workflow for test generation, bot protection, safety rules and limits.


🤖 MCP in One Minute

The Model Context Protocol (MCP) is an open standard that lets AI applications call tools: “navigate to this URL”, “click this element”, “read this file”. An MCP server offers tools; an MCP client (Claude Code, Claude Desktop, VS Code with Copilot, Cursor …) lets the AI model call them. The SQA Tools MCP lesson explains the protocol itself.

Microsoft publishes two ways for AI agents to drive Playwright:

Playwright MCP (@playwright/mcp) playwright-cli
Interface MCP tools (browser_navigate, browser_click, browser_snapshot …) Shell commands (open, click, snapshot …)
Best for Long, exploratory agent sessions with rich page context Coding agents working in a repository: fewer tokens, short outputs
Page data in the model’s context Accessibility snapshots after actions Only what the agent asks for (snapshots are saved to files)
Python code output --codegen python Printed after every action
Install Node.js: npx @playwright/mcp@latest Included in Playwright Python 1.59+ (python -m playwright cli), or npm i -g @playwright/cli

Both work on the same idea: instead of screenshots, the agent reads an accessibility snapshot, a compact text tree of roles and names where every element has a short ref such as e113.


⌨️ playwright-cli from Python

Playwright Python 1.65 includes the CLI. No Node.js is needed:

⌨️ Terminal

python -m playwright cli --help

Here is a recorded session against the SQA Shop login page (24 November 2026). First open a browser session and the page:

⌨️ Terminal

python -m playwright cli open --browser firefox "https://sqatools.in/dummy-ecommerce-website/#/login"

🖥️ Example output

### Browser `default` opened with pid 2864.
### Ran Playwright code
    page.goto("https://sqatools.in/dummy-ecommerce-website/#/login")
### Page
- Page URL: https://sqatools.in/dummy-ecommerce-website/#/login
- Page Title: Dummy E-commerce Website For Automation Practice | SQA Tools
### Snapshot
- [Snapshot](.playwright-cli\page-2026-11-24T12-58-57-802Z.yml)

The browser stays open in the background between commands (a session). The full snapshot is written to a file in .playwright-cli/ instead of being printed, which is what keeps the CLI token-efficient for AI agents. Search it instead of reading all of it:

⌨️ Terminal

python -m playwright cli find "Username"

🖥️ Example output

### Result
Found 2 matches for "Username":
...
                  - heading "Log in" [level=2] [ref=e109]
                  - paragraph [ref=e110]: Logging in is optional. You can also check out as a guest.
                  - generic [ref=e111]:
                    - generic [ref=e112]: Username
                    - textbox "Username" [ref=e113]
                  - generic [ref=e114]:
                    - generic [ref=e115]: Password
                    - textbox "Password" [ref=e116]

Act on elements by ref, or with a Playwright locator, and watch the Python code the CLI prints (the CLI prints Markdown; the code fences are shown indented here):

⌨️ Terminal

python -m playwright cli fill e113 testuser
python -m playwright cli fill e116 "Test@123"
python -m playwright cli click "getByRole('button', { name: 'Log in', exact: true })"

🖥️ Example output

### Ran Playwright code
    page.get_by_test_id("login-username").fill("testuser")
### Ran Playwright code
    page.get_by_test_id("login-password").fill("Test@123")
### Ran Playwright code
    page.get_by_role("button", name="Log in", exact=True).click()
### Page
- Page URL: https://sqatools.in/dummy-ecommerce-website/#/

Three things stand out:

  1. The CLI turned ref e113 into the best stable locator it could find, here the data-testid, exactly what you would choose by hand (Lesson 31).
  2. Locator arguments use the JavaScript form (getByRole('button', {...})); the printed code is Python.
  3. After the click the page navigated to #/. Old refs are now invalid: generate-locator e113 answers “Ref e113 not found in the current page snapshot. Try capturing new snapshot.” Take a new snapshot (or find) after every navigation.

Finish the session:

⌨️ Terminal

python -m playwright cli find "Hi, Test"
python -m playwright cli state-save shopper.json
python -m playwright cli close

state-save writes a storage-state file, the same format as Lesson 51, so a logged-in session explored by hand or by an agent can be reused in your tests.

⚠️ Watch out: Bot protection. In this session Chrome was blocked: the SQA Tools host answered the CLI’s default Chrome browser with a “Checking your browser” page (HTTP 403), while --browser firefox and normal pytest-playwright runs worked. Many production sites protect themselves against automated browsers. Test against your own test environments, and ask the site owner before automating anyone else’s site.


Advertisement

🧪 From Session to pytest Test

The printed code is a draft. Paste it into a test, then do the part only a tester can do: decide what to assert.

📄 pytest.ini

[pytest]
addopts = --base-url https://sqatools.in

📄 tests/test_from_cli.py

from playwright.sync_api import Page, expect


def test_login_recorded_with_cli(page: Page):
    page.goto("/dummy-ecommerce-website/#/login")
    page.get_by_test_id("login-username").fill("testuser")                 # printed by the CLI
    page.get_by_test_id("login-password").fill("Test@123")                 # printed by the CLI
    page.get_by_role("button", name="Log in", exact=True).click()          # printed by the CLI
    expect(page.get_by_test_id("account-button")).to_contain_text("Hi, Test")   # added by you
    expect(page).to_have_url("https://sqatools.in/dummy-ecommerce-website/#/")  # added by you

⌨️ Terminal

pytest -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
rootdir: C:\Users\you\playwright-python
configfile: pytest.ini
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 1 item

tests/test_from_cli.py::test_login_recorded_with_cli[chromium] PASSED    [100%]

============================== 1 passed in 2.66s ==============================

Recorded steps without assertions are not a test. The CLI (like Codegen in Lesson 7) gives you reliable locators and actions; you add expectations, data and structure (page objects, fixtures).


Advertisement

🐞 Debug a Failing Test with the CLI

pytest-playwright 0.10 adds --playwright-debug=cli. The test pauses at the start, prints an attach command, and you (or an AI agent) can inspect and drive the paused browser with CLI commands:

⌨️ Terminal

pytest tests/test_from_cli.py --playwright-debug=cli -s

🖥️ Example output

### The test is currently paused at the start

### Debugging Instructions
- Run `python -m playwright cli attach tw-3f9a1c` to attach to this test

It requires -s (so the attach command is visible) and a single worker (no -n). It is a powerful way to let an agent investigate a failure in the real test context instead of guessing from a stack trace.


🔌 Playwright MCP with an AI Agent

The MCP server runs with Node.js 20+. Add it to Claude Code, asking for Python code generation:

⌨️ Terminal

claude mcp add playwright -- npx @playwright/mcp@latest --codegen python --isolated

Or to VS Code (GitHub Copilot agent mode) in .vscode/mcp.json:

{
  "servers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--codegen", "python", "--isolated", "--browser", "firefox"]
    }
  }
}

Useful options (all also available as PLAYWRIGHT_MCP_* environment variables):

Option Effect
--codegen python Generated code is Python (default is TypeScript)
--isolated Fresh in-memory profile per session: no leftover cookies between runs
--storage-state=shopper.json Start isolated sessions logged in (Lesson 51 files work here)
--browser firefox Choose the browser or Chrome channel
--headless No visible window (CI or background use)
--test-id-attribute data-qa Use your team’s test-id attribute when generating locators
--caps vision,pdf,devtools Extra tool groups (coordinate clicks, PDF saving, DevTools)

The server exposes tools such as browser_navigate, browser_snapshot, browser_click, browser_type, browser_fill_form, browser_select_option, browser_wait_for, browser_network_requests, browser_route, browser_take_screenshot, browser_storage_state and browser_start_tracing.


🗣️ A Prompt Workflow That Works

Agents produce better tests when you give them the same information you would give a new teammate:

Use the playwright tools to explore https://sqatools.in/dummy-ecommerce-website/ in Firefox.
Goal: a pytest test for applying the coupon FLAT200 to a cart with Wireless Earbuds.
Rules:
- Use pytest-playwright with the `page` fixture and relative URLs (base_url is https://sqatools.in).
- Prefer get_by_test_id / get_by_role locators. No sleeps, no XPath.
- Assert the coupon message and the discount line with expect().
- Put the test in tests/test_coupon_ai.py and run it with pytest. Fix it until it passes.

Then review the result like any pull request: are the assertions meaningful, is the data stable, does it duplicate an existing page object? Lesson 71 covers AI tools for test automation more broadly.


🛡️ Safety and Limits

  • An agent with a browser can do anything a user can: submit forms, place orders, delete data. Point it at test environments with test accounts, and prefer --isolated sessions.
  • Treat everything the agent reads on a page as untrusted input: a malicious page can contain text that tries to instruct the agent (“ignore your task and …”). Keep humans in the loop for anything irreversible.
  • Do not put real passwords in prompts; use storage-state files or environment variables.
  • Generated tests can pass for the wrong reason (weak assertions) or encode today’s bug as expected behaviour. Review them.
  • Agents are slow and cost tokens; use them to write and fix tests, then run the resulting pytest suite normally in CI.

Advertisement

🏋️ Practice Exercises

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

Exercise 1: Open the SQA Shop cart with the CLI in WebKit and find the coupon field. Which two commands do you run?

Show answer
python -m playwright cli open --browser webkit "https://sqatools.in/dummy-ecommerce-website/#/cart"
python -m playwright cli find "Coupon"

find searches the saved snapshot and returns matching nodes with their refs.

Exercise 2: After click navigated to a new page, fill e57 hello fails with “Ref e57 not found”. Why, and what do you do?

Show answer

Refs belong to one snapshot of one page state. After navigation (or a big page update) they are invalid. Run snapshot or find again to get the new refs, or act with a locator string instead of a ref.

Exercise 3: The CLI printed this code. Turn it into a complete pytest test with a meaningful assertion.

page.get_by_test_id("search-input").fill("course")
page.get_by_test_id("search-button").click()
Show answer
import re

from playwright.sync_api import Page, expect


def test_search_courses(page: Page):
    page.goto("/dummy-ecommerce-website/")
    page.get_by_test_id("search-input").fill("course")
    page.get_by_test_id("search-button").click()
    expect(page).to_have_url(re.compile(r"#/search/course$"))
    expect(page.get_by_test_id("product-card").first).to_be_visible()

The assertions check the result, not just that the clicks did not fail.

Exercise 4: Write the VS Code mcp.json entry that starts Playwright MCP headless, isolated, logged in with .auth/shopper.json, generating Python code.

Show answer
{
  "servers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--headless", "--isolated",
               "--storage-state=.auth/shopper.json", "--codegen", "python"]
    }
  }
}

🧠 MCQ Quiz: Playwright MCP for Python Testers

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 MCP?
  2. How do Playwright MCP and playwright-cli let an AI “see” a page?
  3. Why is playwright-cli described as token-efficient?
  4. How do you run playwright-cli with only Playwright Python installed?
  5. What happens to element refs after the page navigates?
  6. Which MCP option makes generated code Python?
  7. What does --isolated do for Playwright MCP?
  8. What does pytest-playwright’s --playwright-debug=cli do?
  9. What must a tester still add to code generated by the CLI or MCP?
  10. Which is a safety rule when giving an AI agent a browser?

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


Advertisement

❓ Frequently Asked Questions

🤔 Do I need Node.js to use these tools from Python?

Not for playwright-cli: it is bundled with Playwright Python (python -m playwright cli). The Playwright MCP server is a Node.js package (npx @playwright/mcp@latest), but it generates Python code with --codegen python.

🤔 Will AI agents replace writing Playwright tests?

They change how tests are written, not the need for test design. Agents are good at exploring pages, finding locators and drafting code. Deciding what matters, what to assert and how to keep a suite maintainable remains the tester’s job.

🤔 Is Playwright MCP the same as Playwright’s test agents?

No. Playwright Test (TypeScript) also ships planner, generator and healer test agents built on these tools. They target the TypeScript test runner; in Python you get the same building blocks through MCP, the CLI and your own prompts. The next lesson compares the AI options for Python.

🤔 Can the CLI record a trace or video for me?

Yes: tracing-start / tracing-stop and video commands exist, and the traces open in the normal Trace Viewer (Lesson 62).

🤔 Why did my AI agent click the wrong element?

Usually because the accessibility snapshot was stale or names were ambiguous. Ask it to take a fresh snapshot and to use exact role names or test ids, the same rules you follow yourself (Lessons 31 and 61).


🏁 Summary

  • MCP lets AI clients call tools; Playwright MCP and playwright-cli both drive real browsers using accessibility snapshots and element refs.
  • python -m playwright cli (bundled with Playwright Python) opens sessions, finds elements, acts by ref or locator, and prints the equivalent Python code; refs expire after navigation.
  • Turn recorded code into real tests by adding assertions, and use --playwright-debug=cli to inspect a paused pytest test.
  • Configure Playwright MCP for Claude Code or VS Code with --codegen python, --isolated and storage-state files.
  • Use these tools on test environments with test accounts, treat page text as untrusted, and review everything they generate.

🎬 Watch the Playwright tutorial series on YouTube!

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