How to capture screenshots and videos with Playwright
Posted on
Capturing screenshots and videos of your tests is a super useful feature in Playwright. Whether you're debugging failed tests or simply documenting behavior, Playwright makes it very simple to record what’s happening in the browser.
In this blog post, you'll learn how to:
- Capture screenshots (full page, specific elements)
- Record videos of your tests
- Automatically save them on failure
- Customize where and how they're saved
Let's dive in!
Why Capture Screenshots and Videos?
- Debugging: See what went wrong when a test fails.
- Documentation: Show how features behave visually.
- Demo Recording: Generate videos for demos or presentations.
- CI/CD: Helps when running tests in headless mode on a server.
Prerequisites
Make sure Playwright is already installed and set up. If not, run:
npm init playwright@latest
This will scaffold a project with examples and Playwright Test Runner.
Taking Screenshots in Playwright
1. Capture a full-page screenshot
import { test } from '@playwright/test'; test('Take full-page screenshot', async ({ page }) => { await page.goto('https://playwright.dev'); await page.screenshot({ path: 'fullpage.png', fullPage: true }); });
This captures the entire page, even if it requires scrolling.
2. Capture a screenshot of a specific element
test('Screenshot of specific element', async ({ page }) => { await page.goto('https://playwright.dev'); const logo = page.locator('.navbar__logo'); await logo.screenshot({ path: 'logo.png' }); });
Handy when you're only interested in testing a specific section or component.
3. Automatically take screenshot on test failure
Playwright does this out of the box when using the @playwright/test runner.
To enable this, just add this to your config:
// playwright.config.ts export default { use: { screenshot: 'only-on-failure', // other options: 'on', 'off' }, };
Recording Videos in Playwright
Video recording is done at the browser context level.
1. Enable video recording in config
// playwright.config.ts export default { use: { video: 'on-first-retry', // other options: 'on', 'off', 'retain-on-failure' }, };
This will record the video only if a test fails and retries. You can also set it to 'on' to record every test.
2. Access the video in your test
If you want to get the video file path after the test finishes:
test('Record video and save', async ({ page, context }) => { await page.goto('https://example.com'); // Your test logic here const videoPath = await page.video()?.path(); console.log('Video saved at:', videoPath); });
Customize Output Paths
You can change where screenshots and videos are saved using the config file:
export default { outputDir: 'test-results/', // All artifacts will go here use: { video: 'on', screenshot: 'on', }, };