Overview
Playwright’s Code Generator (codegen) is an interactive tool that records your browser interactions and generates test code automatically. It’s the fastest way to create end-to-end tests by simply using your application as you normally would.Starting Codegen
Basic Usage
With a URL
Command Options
Browser Selection
chromium(default)firefoxorffwebkitorwkcr(alias for chromium)
Target Language
JavaScript/TypeScript
JavaScript/TypeScript
javascript- Plain JavaScript with Playwright Libraryplaywright-test- Playwright Test framework (default)
Python
Python
python- Synchronous Python APIpython-async- Async Python APIpython-pytest- Pytest with Playwright fixtures
Java
Java
java- Java with Playwrightjava-junit- JUnit with Playwright
C#
C#
csharp- C# with Playwrightcsharp-mstest- MSTest with Playwrightcsharp-nunit- NUnit with Playwright
Output to File
Test ID Attribute
Browser Context Options
Codegen supports all standard browser context options to emulate different environments:Device Emulation
Custom Viewport
Color Scheme
Geolocation
Timezone
User Agent
Authentication and Storage
Saving Storage State
Loading Storage State
Network and Proxy
Proxy Server
Ignore HTTPS Errors
Save HAR
How Codegen Works
Based on the implementation in/home/daytona/workspace/source/packages/playwright-core/src/cli/program.ts:563, codegen:
- Launches a browser with specified options (headless or headed mode)
- Enables the recorder through
context._enableRecorder()which activates the recording mode - Creates a trace directory for temporary trace storage
- Opens the Playwright Inspector to display generated code
- Monitors DOM interactions and converts them into test code
- Generates selectors using a priority system:
- Test ID attributes (if configured)
- Role-based selectors
- Text content
- CSS selectors
Codegen uses the same recorder engine that powers the Playwright Inspector, ensuring generated code matches best practices.
Tips for Better Code Generation
Use Test IDs
Add
data-testid attributes to your application and use --test-id-attribute for stable selectors.Slow Down
Don’t rush through actions. Give the page time to load and codegen time to record.
Clean Up
Review and refactor generated code. Extract reusable functions and add assertions.
Save State
Use
--save-storage to capture authentication and reuse it across tests.Example Workflow
See Also
- Inspector - Debug and step through tests
- Trace Viewer - Analyze test execution traces
- UI Mode - Interactive test development environment
