Take a screenshot

Capture a page, the full scrollable area, or a single element.

Save a screenshot of a page or of one element, then reuse it as a baseline for visual regression checks.

The path is the first argument; options go in a second array. Passing the path inside the options array is the JavaScript style, and it does not apply here.

Run it

bash
php content/examples/screenshot.php

Expected artifacts:

text
var/playwright-artifacts/examples/screenshot_example.png

The script also calls screenshot() without a path and prints the returned generated path.

Options

php
$page->screenshot(__DIR__.'/page.png', [
    'fullPage'   => true,        // the whole scrollable area, not just the viewport
    'animations' => 'disabled',  // freeze CSS animations, for stable output
    'type'       => 'jpeg',      // 'png' (default) or 'jpeg'
    'quality'    => 80,          // 0-100, jpeg only
]);

One element

A locator screenshots itself, and nothing around it:

php
$page->locator('.hero-banner')->screenshot(__DIR__.'/hero.png');

Visual regression

Keep the baselines in the repository. On later runs, capture fresh images and compare them with an image-diff tool. Set 'animations' => 'disabled', or a CSS transition will show up as a difference between two runs of the same page.

Naming files automatically

ScreenshotHelper builds a filename from a URL, so successive runs do not overwrite each other:

php
use Playwright\Screenshot\ScreenshotHelper;

$path = ScreenshotHelper::generateFilename('https://example.com', __DIR__.'/shots');
$page->screenshot($path);

It also tidies up after itself: cleanupOldScreenshots() drops files past an age or a count.

What it demonstrates

  • Page::screenshot() captures the viewport or full page.
  • Locator::screenshot() captures one element.
  • Options go in the second PHP argument.
  • Stable screenshot paths matter for CI artifacts.

Go next

Source

screenshot.php
php
<?php

declare(strict_types=1);

/*
 * This file is part of the community-maintained Playwright PHP project.
 * It is not affiliated with or endorsed by Microsoft.
 *
 * (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../../vendor/autoload.php';

use Playwright\Playwright;

$artifactDir = __DIR__.'/../../var/playwright-artifacts/examples';
is_dir($artifactDir) || mkdir($artifactDir, 0777, true);

$context = Playwright::chromium();
$page = $context->newPage();

$page->goto('https://example.com');
echo 'Url: '.$page->url()."\n";

$file = $page->screenshot($artifactDir.'/screenshot_example.png');
echo 'Screenshot saved to: '.$file."\n";

$file = $page->screenshot();
echo 'Screenshot saved to: '.$file."\n";

$page->close();
$context->close();