</>

Technology

Playwright

Difficulty

Beginner

Interview Question

How do you take a screenshot in Playwright?

Answer

Taking Screenshots in Playwright

Full Page Screenshot

TypeScript
// Capture the visible viewport
await page.screenshot({ path: 'screenshot.png' });

// Capture the FULL scrollable page (not just viewport)
await page.screenshot({ path: 'full-page.png', fullPage: true });

Element Screenshot

TypeScript
// Capture only a specific element
await page.locator('.chart-container').screenshot({ path: 'chart.png' });
await page.getByRole('dialog').screenshot({ path: 'modal.png' });

Screenshot in Different Formats

TypeScript
// PNG (default, lossless)
await page.screenshot({ path: 'screenshot.png' });

// JPEG (smaller file size)
await page.screenshot({ path: 'screenshot.jpg', type: 'jpeg', quality: 80 });

Screenshot as Buffer (without saving to file)

TypeScript
const buffer = await page.screenshot();
// Useful for attaching to reports or sending to APIs

Auto-screenshot on Test Failure

In playwright.config.ts:

TypeScript
export default defineConfig({
  use: {
    screenshot: 'only-on-failure', // 'off' | 'on' | 'only-on-failure'
  },
});

Screenshots saved to test-results/ folder automatically.

Screenshot with Clip Region

TypeScript
// Capture only a rectangular region of the page
await page.screenshot({
  path: 'header.png',
  clip: { x: 0, y: 0, width: 1280, height: 100 },
});

Screenshot Inside a Test

TypeScript
import { test, expect } from '@playwright/test';

test('capture checkout page', async ({ page }) => {
  await page.goto('/checkout');

  // Fill cart
  await page.getByRole('button', { name: 'Add to cart' }).click();

  // Take screenshot before asserting
  await page.screenshot({ path: 'test-results/checkout.png', fullPage: true });

  await expect(page.locator('.cart-total')).toBeVisible();
});

Visual Comparison (Snapshot Testing)

TypeScript
// Compare to a baseline screenshot
await expect(page).toMatchSnapshot('homepage.png');
await expect(page.locator('.hero-section')).toMatchSnapshot('hero.png');

First run creates the baseline. Subsequent runs compare and fail if different.

Follow AutomateQA

Related Topics