Playwright CLI
The Complete Guide for QA Engineers - From Installation to Mastery. Learn the standard CLI, the new @playwright/cli for AI agents, and how they compare to MCP.
1 What is Playwright CLI?
The command-line interface that powers Playwright testing workflows
Playwright CLI is the command-line toolset for Microsoft Playwright - the modern browser automation framework. It lets you run tests, record tests via codegen, debug with inspector, view traces, manage browsers, and generate reports - all from your terminal.
npx playwright that ships with @playwright/test, and the new @playwright/cli package built specifically for AI coding agents.
Why QA Engineers Need Playwright CLI
Speed
Run tests, filter by grep, retry failures, and shard across machines - all from a single terminal command. No GUI needed.
Codegen
Record browser interactions and auto-generate test scripts in JS, TS, Python, Java, or C#. Fastest way to bootstrap tests.
CI/CD Native
CLI commands integrate directly into GitHub Actions, Jenkins, GitLab CI. No special plugins required.
2 Two CLIs - Standard vs @playwright/cli
Understanding the two different tools and when to use each
Standard CLI (npx playwright)
Purpose: Running test suites, codegen, debugging, reports
Package: Ships with @playwright/test
Best for: Traditional QA workflows, CI/CD pipelines
# Installation npm init playwright@latest npx playwright install # Common commands npx playwright test npx playwright codegen https://example.com npx playwright show-report npx playwright test --debug
New @playwright/cli (AI Agent CLI)
Purpose: Browser automation for AI coding agents
Package: Separate @playwright/cli package
Best for: Claude Code, Cursor, Copilot, Windsurf integration
# Installation npm install -g @playwright/cli@latest playwright-cli install playwright-cli install --skills # Common commands playwright-cli open https://example.com playwright-cli snapshot playwright-cli click e15 playwright-cli fill e22 "hello"
3 Installation Guide
Step-by-step setup for both CLIs
Standard Playwright CLI
-
Initialize a new Playwright project
npm init playwright@latest
This creates
playwright.config.ts, sample tests, and a GitHub Actions workflow. -
Install browsers
# Install all browsers npx playwright install # Install with OS dependencies (for CI) npx playwright install --with-deps # Install only Chromium npx playwright install chromium
-
Verify installation
npx playwright --version npx playwright test --list
@playwright/cli for AI Agents
-
Install globally
npm install -g @playwright/cli@latest
-
Install browser binaries
playwright-cli install
-
Install Skills (for AI agent discovery)
playwright-cli install --skills
This creates
.claude/skills/playwright-cli/SKILL.mdfor automatic discovery by Claude Code and compatible agents. -
Verify
playwright-cli --version playwright-cli open https://example.com
Full Setup Script (Both CLIs)
#!/bin/bash # 1. Standard Playwright npm init playwright@latest npx playwright install --with-deps # 2. New @playwright/cli npm install -g @playwright/cli@latest playwright-cli install playwright-cli install --skills # 3. Verify both echo "Standard CLI:" npx playwright --version echo "@playwright/cli:" playwright-cli --version
node --version to check.
4 All CLI Commands & Flags
Complete command reference for both CLIs
Standard CLI Commands
| Command | Purpose | Example |
|---|---|---|
npx playwright test | Run all tests | npx playwright test |
test --headed | Run in visible browser | npx playwright test --headed |
test --debug | Debug with Inspector | npx playwright test --debug |
test --ui | Interactive UI mode | npx playwright test --ui |
test --grep | Filter tests by name | npx playwright test --grep "login" |
test --project | Run specific browser | npx playwright test --project=chromium |
test --workers | Parallel workers | npx playwright test --workers=4 |
test --retries | Retry failed tests | npx playwright test --retries=2 |
test --trace on | Record traces | npx playwright test --trace on |
test --shard | Shard across machines | npx playwright test --shard=1/3 |
codegen | Record tests | npx playwright codegen https://app.vwo.com |
show-report | View HTML report | npx playwright show-report |
show-trace | View trace file | npx playwright show-trace trace.zip |
install | Install browsers | npx playwright install chromium |
clear-cache | Clear browser cache | npx playwright clear-cache |
Codegen Flags
| Flag | Purpose | Example |
|---|---|---|
--target | Language output | --target javascript / python / java / csharp |
--output | Save to file | --output tests/login.spec.js |
--browser | Browser to use | --browser firefox |
--device | Emulate device | --device "iPhone 13" |
--viewport-size | Set viewport | --viewport-size "1280,720" |
--color-scheme | Dark/light mode | --color-scheme dark |
--save-storage | Save auth state | --save-storage auth.json |
--load-storage | Load auth state | --load-storage auth.json |
@playwright/cli Commands (AI Agent CLI)
| Category | Commands |
|---|---|
| Browser | open, close, goto, reload |
| Interaction | click, fill, type, drag, select, check, uncheck |
| Inspection | snapshot, screenshot, pdf, eval, console, network |
| Keyboard | press, mousemove, mousewheel |
| Storage | state-save, state-load, cookie-list, localstorage-list |
| Tracing | tracing-start, tracing-stop, video-start, video-stop |
| Session | list, close-all, kill-all |
5 Codegen - Recording Tests
The fastest way to create Playwright tests
# Basic codegen npx playwright codegen https://app.vwo.com # Generate Python test npx playwright codegen --target python https://app.vwo.com # Save directly to file npx playwright codegen --output tests/login.spec.js https://app.vwo.com # Emulate iPhone 13 npx playwright codegen --device "iPhone 13" https://app.vwo.com # Dark mode + timezone npx playwright codegen --color-scheme dark --timezone "Asia/Kolkata" https://app.vwo.com # Save authentication state after login npx playwright codegen --save-storage auth.json https://app.vwo.com # Reuse saved auth in next session npx playwright codegen --load-storage auth.json https://app.vwo.com
How Codegen Generates Locators
Codegen automatically picks the most resilient locator strategy, in this order of priority:
| Priority | Strategy | Example |
|---|---|---|
| 1 | Role-based | getByRole('button', { name: 'Login' }) |
| 2 | Text-based | getByText('Welcome back') |
| 3 | Test ID | getByTestId('login-btn') |
| 4 | Placeholder | getByPlaceholder('Enter email') |
| 5 | CSS Selector | locator('#login-form input') |
6 MCP vs CLI - Complete Comparison
When to use Playwright MCP Server vs the CLI tool
| Aspect | Playwright MCP Server | Playwright CLI | @playwright/cli (New) |
|---|---|---|---|
| Architecture | JSON-RPC over stdio/SSE, runs inside AI agent process | Standard CLI, one-shot execution per command | Client-daemon over Unix sockets, persistent sessions |
| Token Usage | ~115K tokens per 30 actions (snapshots in context) | N/A (not used with AI agents) | ~25K tokens per 30 actions (snapshots to disk, 4.6x savings) |
| Setup | Add to MCP config (settings.json), auto-starts | npm init playwright@latest |
npm i -g @playwright/cli + skills install |
| Browser Lifetime | Managed by MCP server, per-tool-call | Starts/stops per command | Persistent daemon, survives between commands |
| Best For | AI agents doing interactive testing, live exploration | CI/CD, manual test runs, codegen, reports | AI agents needing token-efficient browser automation |
| IDE Support | Claude Code, Cursor, Windsurf (via MCP config) | VS Code Extension, any terminal | Claude Code, Cursor, Copilot, Windsurf (via skills) |
| Codegen | No built-in codegen | Full codegen with Inspector UI | YAML flow logging, auto-generates code |
| Multi-browser | One browser per session | Parallel via --project and --shard | Named sessions, parallel instances |
| Tracing | Supported via tool calls | --trace on flag |
tracing-start / tracing-stop |
| Network Mocking | Not directly supported | Via test code (page.route) | route command |
Decision Matrix: Which Tool to Use?
Use Standard CLI When:
- Running tests in CI/CD
- Recording tests with codegen
- Viewing reports and traces
- Manual QA workflows
- Installing/managing browsers
Use MCP Server When:
- AI agent needs live browser access
- Interactive test exploration
- Context window is not a concern
- Already using MCP infrastructure
- Need rich snapshot data in-context
Use @playwright/cli When:
- AI agent needs token efficiency
- Persistent browser sessions needed
- Complex multi-step automation
- Network mocking required
- State save/restore workflows
7 IDE & AI Tool Integration
Setting up Playwright CLI across VS Code, Claude Code, Codex, Cursor, and Windsurf
VS Code - Playwright Test Extension
-
Install the extension
Search for "Playwright Test for VS Code" in the Extensions panel and install it.
-
Key Features
- Record New: Click "Record New" in the Testing sidebar to open a browser and generate a test file while you interact.
- Record at Cursor: Place your cursor in an existing test and click "Record at Cursor" to append new actions.
- Pick Locator: Hover over elements in the browser to see locators, click to copy.
- Show Trace: Right-click a test result to view its trace inline.
-
Run from Terminal
# All standard CLI commands work in VS Code terminal npx playwright test --headed npx playwright codegen https://app.vwo.com npx playwright show-report
Claude Code Integration
Claude Code supports Playwright via two methods: MCP Server and @playwright/cli Skills.
Method 1: MCP Server (in settings.json)
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
}
This gives Claude Code direct browser_snapshot, browser_click, browser_type etc. tools.
Method 2: @playwright/cli with Skills
# Install CLI + skills npm install -g @playwright/cli@latest playwright-cli install --skills # This creates .claude/skills/playwright-cli/SKILL.md # Claude Code auto-discovers and uses it
Method 3: Custom Skill File
Create your own skill (see Skill File section below) to customize how Claude Code uses the CLI.
Cursor Integration
-
MCP Config
Open Cursor Settings > MCP and add:
{ "mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest"] } } } -
@playwright/cli Skills
npm install -g @playwright/cli@latest playwright-cli install --skills
Cursor's AI composer auto-detects the skill file in
.cursor/skills/or.claude/skills/. -
Terminal commands
# Use standard CLI in Cursor's terminal npx playwright test --headed npx playwright codegen https://app.vwo.com
Windsurf (Codeium) Integration
-
MCP Server Setup
Add to Windsurf's MCP configuration:
{ "mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest"] } } } -
@playwright/cli
npm install -g @playwright/cli@latest playwright-cli install --skills
Windsurf's Cascade AI detects skills and offers browser automation commands.
-
Use in Chat
Ask Cascade: "Open app.vwo.com and record a login test" - it will use the detected Playwright CLI tools.
OpenAI Codex CLI Integration
-
Setup
Codex CLI works with terminal commands. Install both CLIs:
npm init playwright@latest npm install -g @playwright/cli@latest
-
Usage
Ask Codex to generate and run Playwright CLI commands:
# Example Codex prompts: "Generate a Playwright test for app.vwo.com login" "Run my Playwright tests with retries" "Record a codegen session for the checkout flow" -
Integration
Codex reads your
playwright.config.jsand test files to understand your project structure. It can generate npx playwright commands directly.
8 Three Hands-On Projects
Complete walkthroughs with code samples
Project 1: Automate Login on app.vwo.com using Playwright CLI
Beginner Codegen + ManualObjective
Use Playwright CLI codegen to record a login flow on app.vwo.com, then refine the generated test into a production-ready spec file.
Step 1: Record with Codegen
# Open codegen targeting app.vwo.com npx playwright codegen https://app.vwo.com # Save output directly to a file npx playwright codegen --output tests/vwo_login.spec.js https://app.vwo.com
Step 2: Generated Code (Typical Output)
import { test, expect } from '@playwright/test'; test('VWO Login Test', async ({ page }) => { // Navigate to VWO login page await page.goto('https://app.vwo.com'); // Fill email field await page.getByPlaceholder('e.g. [email protected]') .fill('[email protected]'); // Fill password field await page.getByPlaceholder('Enter password') .fill('your_password_here'); // Click Sign In button await page.getByRole('button', { name: 'Sign in to VWO' }) .click(); // Assert successful login - dashboard is visible await expect(page).toHaveURL(/dashboard/); });
Step 3: Refine into Framework Pattern
// tests/vwo_login.spec.js - Production-ready version import { test, expect } from '@playwright/test'; // Test data (move to .env or config in real projects) const LOGIN_URL = 'https://app.vwo.com'; const VALID_EMAIL = process.env.VWO_EMAIL || '[email protected]'; const VALID_PASS = process.env.VWO_PASS || 'TestPass123'; test.describe('VWO Login Suite', () => { test.beforeEach(async ({ page }) => { await page.goto(LOGIN_URL); }); test('TC-001: Successful login with valid credentials', async ({ page }) => { await page.getByPlaceholder('e.g. [email protected]') .fill(VALID_EMAIL); await page.getByPlaceholder('Enter password') .fill(VALID_PASS); await page.getByRole('button', { name: 'Sign in to VWO' }) .click(); await expect(page).toHaveURL(/dashboard/); }); test('TC-002: Login fails with invalid password', async ({ page }) => { await page.getByPlaceholder('e.g. [email protected]') .fill(VALID_EMAIL); await page.getByPlaceholder('Enter password') .fill('WrongPassword'); await page.getByRole('button', { name: 'Sign in to VWO' }) .click(); await expect( page.getByText('Your email or password is incorrect') ).toBeVisible(); }); test('TC-003: Login fails with empty fields', async ({ page }) => { await page.getByRole('button', { name: 'Sign in to VWO' }) .click(); // Verify validation error appears await expect( page.getByText('required') ).toBeVisible(); }); });
Step 4: Run the Tests
# Run all login tests npx playwright test tests/vwo_login.spec.js --headed # Run with trace for debugging npx playwright test tests/vwo_login.spec.js --trace on # Run on specific browser npx playwright test tests/vwo_login.spec.js --project=chromium # Debug mode with Inspector npx playwright test tests/vwo_login.spec.js --debug
Project 2: Generate E2E Test Suite with Codegen
Intermediate Full SuiteObjective
Use codegen to generate a complete E2E test suite for the-internet.herokuapp.com covering multiple pages, then run with reporting and tracing.
Step 1: Record Multiple Flows
# Record form authentication flow npx playwright codegen \ --output tests/auth.spec.js \ https://the-internet.herokuapp.com/login # Record dropdown interaction npx playwright codegen \ --output tests/dropdown.spec.js \ https://the-internet.herokuapp.com/dropdown # Record checkbox interactions npx playwright codegen \ --output tests/checkboxes.spec.js \ https://the-internet.herokuapp.com/checkboxes # Record on mobile viewport npx playwright codegen \ --device "iPhone 13" \ --output tests/mobile_nav.spec.js \ https://the-internet.herokuapp.com
Step 2: Save Auth State for Reuse
# Login once, save state npx playwright codegen \ --save-storage auth-state.json \ https://the-internet.herokuapp.com/login # Now use saved state in future codegen sessions npx playwright codegen \ --load-storage auth-state.json \ https://the-internet.herokuapp.com/secure
Step 3: Configure and Run Full Suite
// playwright.config.js module.exports = { testDir: './tests', timeout: 30000, retries: 1, workers: 3, reporter: [ ['html', { open: 'never' }], ['json', { outputFile: 'reports/results.json' }] ], use: { baseURL: 'https://the-internet.herokuapp.com', trace: 'on-first-retry', screenshot: 'only-on-failure', }, projects: [ { name: 'chromium', use: { browserName: 'chromium' } }, { name: 'firefox', use: { browserName: 'firefox' } }, { name: 'webkit', use: { browserName: 'webkit' } }, ], };
# Run full suite across all browsers npx playwright test # View the HTML report npx playwright show-report # Run only auth tests with retries npx playwright test --grep "auth" --retries=2 # Shard across 3 CI machines npx playwright test --shard=1/3 npx playwright test --shard=2/3 npx playwright test --shard=3/3
Project 3: AI Agent + Playwright CLI Workflow
Advanced AI IntegrationObjective
Use @playwright/cli with an AI agent (Claude Code) to interactively automate and test a web application with persistent sessions and token-efficient snapshots.
Step 1: Setup @playwright/cli with Skills
# Install and setup npm install -g @playwright/cli@latest playwright-cli install playwright-cli install --skills # Verify skill file was created cat .claude/skills/playwright-cli/SKILL.md
Step 2: Interactive Session (via Claude Code or Terminal)
# Open a persistent session playwright-cli open https://app.vwo.com -s=vwo-login --persistent # Take an accessibility snapshot (saved to disk, not stdout) playwright-cli snapshot -s=vwo-login # Fill the email field (using snapshot ref e.g., e15) playwright-cli fill e15 "[email protected]" -s=vwo-login # Fill password (ref e22 from snapshot) playwright-cli fill e22 "MyPassword123" -s=vwo-login # Click the Sign In button (ref e28) playwright-cli click e28 -s=vwo-login # Take a screenshot to verify playwright-cli screenshot -s=vwo-login # Save auth state for reuse playwright-cli state-save vwo-auth.json -s=vwo-login # Start tracing for debugging playwright-cli tracing-start -s=vwo-login # ... do more actions ... # Stop tracing and save playwright-cli tracing-stop -s=vwo-login --output trace.zip
Step 3: AI Agent Workflow Example
// Example: What happens when you tell Claude Code // "Login to app.vwo.com and verify the dashboard loads" // Claude Code with @playwright/cli skill will: // 1. Run: playwright-cli open https://app.vwo.com -s=test // 2. Run: playwright-cli snapshot -s=test // 3. Read snapshot file (25K tokens vs 115K with MCP) // 4. Identify email field ref, fill it // 5. Identify password field ref, fill it // 6. Click sign-in button ref // 7. Take screenshot to verify dashboard // 8. Report results back to you
MCP vs CLI Token Comparison
9 10 Exercises for Practice
Hands-on tasks to build your Playwright CLI mastery
Task: Create a basic Playwright project and run the sample tests.
mkdir my-pw-project && cd my-pw-project npm init playwright@latest npx playwright test npx playwright show-report
Expected: See test results in terminal and HTML report opens in browser.
Task: Use codegen to record a test that searches Google for "Playwright testing" and verifies results appear.
npx playwright codegen --output tests/google.spec.js https://google.com
Steps: Type in search box, press Enter, verify results. Save and run.
Task: Run your tests on Chromium, Firefox, and WebKit using CLI flags.
# Run on each individually npx playwright test --project=chromium npx playwright test --project=firefox npx playwright test --project=webkit # Run all three at once npx playwright test
Expected: Compare results across all three browsers.
Task: Record a mobile test on iPhone 13 and iPad Pro.
npx playwright codegen --device "iPhone 13" https://example.com npx playwright codegen --device "iPad Pro 11" https://example.com
Expected: Browser opens with device viewport. Generated code includes device config.
Task: Create an intentionally failing test, then use debug mode and trace to find the issue.
// Create a test that will fail test('should find nonexistent element', async ({ page }) => { await page.goto('https://example.com'); await expect(page.locator('#does-not-exist')).toBeVisible(); }); # Debug it npx playwright test --debug # Or use trace npx playwright test --trace on npx playwright show-trace test-results/*/trace.zip
Task: Create 5 tests with different names and practice filtering them.
# Run only tests with "login" in name npx playwright test --grep "login" # Exclude tests with "slow" in name npx playwright test --grep-invert "slow" # Run specific file npx playwright test tests/auth.spec.js # List all tests without running npx playwright test --list
Task: Use codegen to login to a site, save the auth state, then reuse it in a new session.
# Step 1: Login and save state npx playwright codegen --save-storage auth.json https://the-internet.herokuapp.com/login # Step 2: Use saved state (skip login) npx playwright codegen --load-storage auth.json https://the-internet.herokuapp.com/secure
Task: Simulate a CI pipeline by running tests with CI-friendly flags.
# CI-style execution npx playwright test \ --reporter=json \ --output-folder=ci-results \ --workers=4 \ --retries=2 \ --trace=on-first-retry \ --forbid-only # Sharding for parallel CI jobs npx playwright test --shard=1/3 npx playwright test --shard=2/3 npx playwright test --shard=3/3
Task: Install @playwright/cli and automate a form fill using interactive commands.
npm install -g @playwright/cli@latest playwright-cli install # Open a page playwright-cli open https://the-internet.herokuapp.com/login -s=demo # Take snapshot to see element refs playwright-cli snapshot -s=demo # Fill username and password using refs from snapshot playwright-cli fill <username-ref> "tomsmith" -s=demo playwright-cli fill <password-ref> "SuperSecretPassword!" -s=demo playwright-cli click <button-ref> -s=demo # Screenshot to verify playwright-cli screenshot -s=demo
Task: Create a custom reporter and use it via CLI flags.
// reporters/my-reporter.js class MyReporter { onBegin(config, suite) { console.log(`Starting ${suite.allTests().length} tests`); } onTestEnd(test, result) { console.log(`${result.status}: ${test.title}`); } onEnd(result) { console.log(`Finished: ${result.status}`); } } module.exports = MyReporter; # Use via CLI npx playwright test --reporter=./reporters/my-reporter.js
10 Quiz - Test Your Knowledge
10 questions to check your understanding
Q1: Which command records browser interactions and generates test code?
npx playwright codegen [url] opens a browser and the Playwright Inspector, generating code as you interact.Q2: What is the primary advantage of @playwright/cli over MCP for AI agents?
Q3: Which flag runs tests in a visible browser window?
npx playwright test --headed runs tests in headed (visible) mode.Q4: How do you save authentication state with codegen?
--save-storage auth.json saves cookies, localStorage, and sessionStorage.Q5: What is the architecture of @playwright/cli?
Q6: Which command opens the interactive test runner in VS Code?
--ui opens the Playwright UI Mode for interactive test running and debugging.Q7: How do you run tests on only Firefox using CLI?
--project=firefox runs tests on the Firefox project as defined in playwright.config.Q8: What does the codegen --target python flag do?
--target python generates the recorded interactions as Python code (using pytest-playwright syntax).Q9: In @playwright/cli, what does the -s flag specify?
-s=name specifies a named session. Multiple sessions can run in parallel.Q10: Which locator strategy does Playwright codegen prioritize first?
getByRole first, then getByText, then getByTestId, then CSS selectors.11 10 Interview Questions & Answers
Commonly asked Playwright CLI questions in QA interviews
Answer: Playwright CLI is the command-line interface that ships with the @playwright/test package. While Playwright as a library provides APIs to write test scripts programmatically (page.goto, page.click, etc.), the CLI provides tools to run those tests (npx playwright test), record new tests (codegen), debug them (--debug), view reports (show-report), and manage browsers (install). The CLI is the operational layer on top of the library.
Answer: npx playwright codegen [url] opens a browser and the Playwright Inspector side by side. As you interact with the browser (click, type, navigate), the Inspector generates test code in real-time. Use cases include: rapid test prototyping, discovering correct locators for complex UIs, generating tests in multiple languages (JS, Python, Java, C#), testing mobile viewports via --device flag, and saving auth state via --save-storage for reuse.
Answer: Define projects in playwright.config.js for each browser (chromium, firefox, webkit). Then run npx playwright test to execute on all, or npx playwright test --project=chromium for a specific one. For CI, use sharding: --shard=1/3, --shard=2/3, --shard=3/3 to distribute tests across parallel machines.
Answer:
- --headed: Runs tests with a visible browser window. Tests execute at full speed. Good for watching test execution.
- --debug: Opens Playwright Inspector alongside the browser. Tests pause at each step, letting you step through, inspect locators, and evaluate expressions. Best for debugging failures.
- --ui: Opens an interactive web UI with a test list, timeline, trace viewer, and source code view. You can run, filter, and watch tests. Best for development workflow.
Answer: Use npx playwright test --retries=2 to retry failed tests up to 2 times. Combine with --trace on-first-retry to capture traces only when a retry happens (saving disk space). In CI, use --reporter=json to track flaky test patterns. The --forbid-only flag prevents accidentally committed test.only from running in CI.
Answer: The Trace Viewer is a post-mortem debugging tool. Record traces with npx playwright test --trace on. View with npx playwright show-trace trace.zip. It shows: a timeline of every action, DOM snapshots before/after each action, network requests, console logs, and test source code. It is essential for debugging CI failures where you cannot reproduce locally.
Answer: @playwright/cli is a separate npm package purpose-built for AI coding agents (Claude Code, Cursor, Copilot). Key differences: (1) Uses client-daemon architecture with persistent browser sessions vs one-shot execution. (2) Writes snapshots to disk (~4.6x token reduction vs MCP). (3) Supports named sessions via -s flag for parallel automation. (4) Has 50+ interactive commands (click, fill, snapshot) vs the standard CLI's test-runner focus. Choose standard CLI for CI/CD test runs, @playwright/cli for AI agent workflows.
Answer: Key CI flags: --reporter=json,html for machine-readable + human-readable output; --workers=4 for parallelism; --retries=2 for flaky test resilience; --shard=1/N for distributing across N machines; --forbid-only to prevent test.only leaks. For Docker: npx playwright install --with-deps installs browser + OS dependencies. GitHub Actions has a dedicated playwright action for caching browsers.
Answer: Playwright MCP (Model Context Protocol) Server provides browser automation as tool calls within an AI agent's context. Use MCP when: the AI agent needs real-time browser state in its context window, doing interactive exploration, or already using MCP infrastructure. Use CLI when: running in CI/CD, recording tests with codegen, viewing reports/traces, or when token efficiency matters (@playwright/cli uses 4.6x fewer tokens than MCP).
Answer: Codegen uses a priority-based locator selection: (1) getByRole - most resilient, uses ARIA roles; (2) getByText - visible text content; (3) getByTestId - data-testid attributes; (4) getByPlaceholder - input placeholders; (5) CSS selectors - last resort. This hierarchy produces tests that are less brittle and more maintainable. The VS Code extension's "Pick Locator" feature uses the same algorithm to suggest locators on hover.
12 Playwright CLI Skill File
Ready-to-use skill for Claude Code / AI agents
How to Install
# Create the skill directory mkdir -p .claude/skills/playwright-cli # Copy the SKILL.md content below into this file: # .claude/skills/playwright-cli/SKILL.md
SKILL.md Content
---
name: playwright-cli
description: >
Automate browser interactions using Playwright CLI tools.
Covers both standard CLI (npx playwright) for test execution,
codegen, debugging, reporting, and the new @playwright/cli
for AI-agent-friendly persistent browser sessions.
triggers:
- playwright
- codegen
- browser test
- e2e test
- record test
- login automation
- headed mode
- trace viewer
- html report
---
# Playwright CLI Skill
## Standard CLI Commands (npx playwright)
### Run Tests
```bash
npx playwright test # Run all tests
npx playwright test --headed # Visible browser
npx playwright test --debug # Debug with Inspector
npx playwright test --ui # Interactive UI mode
npx playwright test --grep "login" # Filter by name
npx playwright test --project=chromium # Specific browser
npx playwright test --workers=4 # Parallel execution
npx playwright test --retries=2 # Retry failures
npx playwright test --trace on # Record traces
npx playwright test --shard=1/3 # Shard for CI
npx playwright test --list # List tests (no run)
```
### Record Tests (Codegen)
```bash
npx playwright codegen [url] # Record test
npx playwright codegen --output tests/my.spec.js # Save to file
npx playwright codegen --target python # Python output
npx playwright codegen --device "iPhone 13" # Mobile
npx playwright codegen --save-storage auth.json # Save auth
npx playwright codegen --load-storage auth.json # Reuse auth
```
### Reports & Debugging
```bash
npx playwright show-report # Open HTML report
npx playwright show-trace trace.zip # View trace file
npx playwright install # Install browsers
npx playwright install --with-deps # + OS dependencies
npx playwright clear-cache # Clear browser cache
```
## @playwright/cli (AI Agent CLI)
### Setup
```bash
npm install -g @playwright/cli@latest
playwright-cli install
playwright-cli install --skills
```
### Interactive Commands
```bash
playwright-cli open [url] -s=[session] # Open page
playwright-cli snapshot -s=[session] # A11y snapshot
playwright-cli screenshot -s=[session] # Screenshot
playwright-cli click [ref] -s=[session] # Click element
playwright-cli fill [ref] "text" -s=[s] # Fill input
playwright-cli type [ref] "text" -s=[s] # Type text
playwright-cli press Enter -s=[session] # Press key
playwright-cli select [ref] "val" -s=[s] # Select option
playwright-cli state-save file.json -s=[s] # Save state
playwright-cli state-load file.json -s=[s] # Load state
playwright-cli close -s=[session] # Close page
```
## Locator Priority (Codegen)
1. getByRole('button', { name: '...' })
2. getByText('...')
3. getByTestId('...')
4. getByPlaceholder('...')
5. CSS selectors (last resort)
## Common Patterns
### Login Automation
```javascript
test('login test', async ({ page }) => {
await page.goto('https://app.example.com');
await page.getByPlaceholder('Email').fill('[email protected]');
await page.getByPlaceholder('Password').fill('pass123');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/dashboard/);
});
```
### CI/CD Configuration
```bash
npx playwright test \
--reporter=json,html \
--workers=4 \
--retries=2 \
--trace=on-first-retry \
--forbid-only
```