Writing locators by hand is tedious. Inspecting elements, guessing CSS selectors, running the test, finding out the selector is wrong, repeating. Playwright has a built-in code generator that records your actions and generates test code.
# Launch codegen -- opens a browser and an inspector window
npx playwright codegen https://testerrank.com/shopping
# Codegen with specific viewport
npx playwright codegen --viewport-size=1280,720 https://testerrank.com/banking
# Codegen for mobile emulation
npx playwright codegen --device="iPhone 13" https://testerrank.comRun the codegen command with your target URL
A browser window and an inspector panel open side by side
Interact with the page -- click buttons, fill forms, navigate
The inspector generates TypeScript/JavaScript code for every action
Copy the generated code into your test file
Refine the code -- rename variables, add assertions, remove redundant steps
Codegen is a starting point, not the final product. The generated code works but may use overly specific selectors. Always review and simplify the locators. Replace CSS selectors with getByRole or getByLabel where possible.
Q: How do you write Playwright tests faster?
A: I use codegen to bootstrap the test -- it records my actions and generates the initial code with correct locators. Then I refine: replace fragile selectors with role-based locators, add meaningful assertions, extract repeated patterns into page objects, and add test data setup. Codegen handles the boring part, I handle the smart part.
Key Point: Codegen records your browser actions and generates test code. Use it to start fast, then refine the output.