How to Capture Screenshots and Videos Using Playwright

Understand how to take screenshots and record videos in Playwright, with clear examples and practical guidance for debugging tests.

Get Started free
How To Capture Screenshots & Videos using Playwright
Home Guide How To Capture Screenshots & Videos using Playwright

How To Capture Screenshots & Videos using Playwright

A failing Playwright test can feel like a dead end when there’s nothing visual to explain what actually happened on the screen.

Take a familiar scenario: a UI test fails in CI, yet the same test passes flawlessly on your machine. No logs point to the issue. The report simply says a button wasn’t clicked in time.

Maybe an animation briefly covered it.

Maybe the page scrolled at the wrong moment.

Maybe a modal flashed and disappeared before the next step fired.

Without visual proof, the cause remains guesswork.

This is where screenshots and videos in Playwright become indispensable. They show exactly what the browser saw-turning invisible failures into clear, actionable evidence.

A single screenshot shows the exact state of the page at failure. A video reveals the full sequence-every transition, delay, and unexpected shift.

Overview

Points to note While capturing Screenshots & Videos in Playwright

  • Use page.screenshot() to capture a basic screenshot of the current browser state.
  • Capture full-page screenshots with the fullPage: true option for complete UI visibility.
  • Take element-level screenshots using locator.screenshot() for focused UI inspection.
  • Generate in-memory screenshot buffers for processing or encoding workflows.
  • Configure Playwright to capture screenshots only on failures or retries to reduce noise.
  • Configure video recording through the video option or recordVideo in context for full test playback.
  • Adjust video mode, size, and directory to control recording behavior and storage.
  • Retrieve saved video file paths after test execution using page.video().path().

This guide explains how to capture screenshots and record videos in Playwright, and best practices to follow while implementing these.

What are Visual Artifacts in Test Automation (Screenshots vs Videos)

Screenshots are static images of the browser state at a specific moment, while videos record the execution flow of a test.

Screenshots are ideal for pinpointing UI mismatches – e.g., layout shifts, incorrect styles – whereas videos capture dynamic interactions such as animations, transitions or unexpected user flows.

Using them together gives a fuller picture of what happens during test execution, aiding root-cause analysis.

Why Capture Screenshots and Videos in Playwright?

Capturing visual artifacts in Playwright enhances several aspects of test automation:

  • Helps diagnose flaky tests by visualizing what the browser experienced when a failure occurred.
  • Provides evidence when reporting UI regressions or layout changes during maintenance.
  • Serves as documentation of key flows (e.g., user login, checkout) to support development or stakeholder review.
  • Enables easier comparison of UI behaviour across browsers/devices when combined with cross-platform runs.

Setup and Configuration for Capture Screenshots and Videos in Playwright

Learn how screenshots and videos in Playwright are captured during test execution.

Installing Playwright and creating a basic test

Begin by installing Playwright in your project:

npm install -D @playwright/test npx playwright install

Then create a simple test file, for example example.spec.ts:

import { test, expect } from ‘@playwright/test’;test(‘basic test’, async ({ page }) => {
await page.goto(‘https://example.com’);
await expect(page).toHaveTitle(/Example/);
});

Configuring screenshot and video options in playwright.config.ts

In playwright.config.ts, enable screenshots/videos globally or per-project:

import { defineConfig } from ‘@playwright/test’;export default defineConfig({
use: {
screenshot: ‘only-on-failure’, // capture screenshot when test fails
video: { mode: ‘retain-on-failure’ } // record video only when test fails
},
});

The official docs note that video recording modes include ‘off’, ‘on’, ‘retain-on-failure’, and ‘on-first-retry’.

These configuration settings establish a baseline for capturing visual artifacts without overwhelming your storage or workflow.

BrowserStack Automate is a cloud-based testing tool, that streamlines the setup phase by providing ready-to-use real browsers and devices, eliminating the need to configure or maintain local environments.

With instant cloud access, detailed logs, videos, and network data captured automatically, it ensures every test starts with consistent conditions and reliable visual artifacts, without handling browser updates or device setup.

Talk to an Expert

Capturing Screenshots with Playwright

Capturing screenshots in Playwright gives a clear snapshot of the browser’s state at any moment, helping identify UI issues with precision. Here are the steps to follow:

Basic screenshot API usage (page.screenshot)

The core method for capturing screenshots:

await page.screenshot({ path: ‘screenshot.png’ });

You can optionally specify options such as format or quality.

Full-page, viewport, element-level, and buffer captures

Full-page:

await page.screenshot({ path: ‘fullpage.png’, fullPage: true });

Element:

 await page.locator(‘.header’).screenshot({ path: ‘header.png’ });

Buffer-capture (in-memory):

const buffer = await page.screenshot(); console.log(buffer.toString(‘base64’));

Screenshot on failures or retries

Using config to capture only on failures (or on first retry) limits noise and focuses artifacts on problematic runs. This strategy helps maintain manageable disk usage and meaningful outputs for analysis.

Recording Videos with Playwright

Recording videos in Playwright provides a continuous view of each test run, making it easier to trace interactions, spot timing issues, and understand failures end-to-end.

Configuring video recording (video mode, size, directory)

Video capture is supported via the video option in config or via recordVideo in context creation:

export default defineConfig({ use: {
video: { mode: ‘on-first-retry’, size: { width: 640, height: 480 } }
},
});

Or during context:

const context = await browser.newContext({ recordVideo: { dir: ‘videos/’, size: { width: 640, height: 480 } }
});

Accessing and saving recorded video files

After the browser context is closed, video files are persisted. You can retrieve the path:

const videoPath = await page.video().path();

When and what to record?

Recording videos of every test can be heavy on storage. Recommended practices:

  • Record only when tests fail or on first retry.
  • Enable video recording for longer or critical flows rather than every trivial test.
  • Configure directory structure and cleanup policy to manage disk usage effectively.

Integrating Visual Captures into Your Test Pipeline

Integrating screenshots and videos into the test pipeline ensures every run produces actionable visual evidence, strengthening debugging and transparency across teams.

Using screenshots/videos for debugging and bug reports

When a test fails, share the screenshot or video along with logs. Visual evidence provides context that logs alone may miss. Example: layout shift occurs only after a hover interaction, visible in the video.

Incorporating into CI/CD workflows

Configure your CI to archive screenshots/videos as artifacts when a run completes. This provides a historical record of test results and helps when tracing regressions back across runs.

Visual regression testing with screenshots/videos

With screenshot functionality, use assertions like:

await expect(page).toHaveScreenshot(‘landing.png’);

This enables comparison of current UI state with a baseline. Storing videos enables reviewing interactions between runs and spotting UI behaviour shifts.

Troubleshooting Common Issues in Capturing Screenshots and Videos in Playwright

Troubleshooting screenshot and video issues in Playwright involves identifying why artifacts fail to save, grow too large, or impact performance, and applying targeted fixes to keep captures reliable.

  • Large video file sizes and storage drainage: High-resolution videos or recording every test can quickly consume storage. Mitigate this by limiting recording to failure cases or shorter tests, compressing videos or purging old artifacts.
  • Screenshots/videos missing or not saved: Ensure that contexts and pages are closed properly so that Playwright flushes artifacts to disk. Also verify file paths, permissions and config modes (e.g., video: ‘off’).
  • Performance impact during capture: Capturing high-resolution video or full-page screenshots increases overhead. Use lower resolutions when possible and avoid capturing at every step in high-parallel testing scenarios.

Best Practices and Optimization Tips for Capturing Screenshots/Videos in Playwright

Following best practices for screenshots and videos in Playwright helps maintain consistent output, control storage use, and ensure visual artifacts remain accurate and useful across environments.

  • Capture only what’s needed (for failures, key user flows) to avoid excessive storage.
  • Name and organize output artifacts consistently (e.g., screenshots/{testName}-{browser}.png) for easier tracking.
  • Clean up old artifacts regularly or archive them to long-term storage.
  • Use buffered screenshot capture when processing images in-memory (e.g., for image diffing) rather than saving to file.
  • For visual regression, maintain a stable baseline environment (consistent screen size, OS, browser version) since screenshot comparisons depend on determinism.

BrowserStack Automate is a cloud-based testing tool that reinforces best practices by running Playwright tests on stable, managed infrastructure that keeps screenshots and videos consistent across browsers and devices.

High-scale parallel execution speeds up visual validation, while the unified debugging dashboard organizes artifacts for quick review. With built-in logs, videos, and seamless CI/CD integration, teams can optimize capture workflows without worrying about maintenance or cross-browser reliability.

Playwright Testing

How BrowserStack helps in Testing Screenshots/Videos in Playwright?

Testing screenshots and videos at scale requires reliable environments, predictable rendering, and consistent artifact storage.

Local setups often introduce variations-different GPU drivers, mismatched browser versions, unstable networks, or rendering quirks that appear only at scale. BrowserStack removes these variables by providing managed environments with real devices, consistent browser configurations, scalable infrastructure, deep debugging tools, and a self-healing test layer that keeps Playwright’s screenshots and videos stable and reproducible across runs.

BrowserStack Automate is a cloud-based testing tool that strengthens Playwright’s screenshot and video workflows through multiple layers of support.

Here’s how it improves accuracy, coverage, and debugging efficiency:

  • Runs Playwright tests on real browsers and 3500+ real mobile devices to generate accurate screenshots and videos.
  • Provides consistent OS, browser, and device configurations so visual artifacts remain stable across runs.
  • Automatically stores screenshots, videos, logs, and traces in a unified dashboard for quick debugging.
  • Supports high-scale parallel test execution to capture visuals across multiple environments simultaneously.
  • Offers precise video playback with timestamps and detailed logs to diagnose UI failures.
  • Eliminates browser and device maintenance, ensuring updated environments without local setup.
  • Integrates natively with Playwright Test, preserving all screenshot and video options without extra configuration.

Try BrowserStack Automate

Conclusion

Capturing screenshots and videos with Playwright transforms visual testing from a manual afterthought into an integral part of the automation flow. When used strategically-configured for key flows, combined with CI/CD pipelines, and optionally scaled via BrowserStack Automate-it raises the transparency, diagnosability and reliability of web test suites.

Tags
Playwright
Are Your Playwright Tests Failing Without Visual Clues?
Run Playwright on BrowserStack Automate to test and validate screenshots and videos across real browsers and devices, ensuring consistent, reliable visual artifacts.

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord