ScreenshotNeo

BlogHow-to

How to Take Screenshots with Selenium WebDriver and PHPUnit

Save screenshots with php-webdriver, capture failures before PHPUnit closes the browser, and keep the resulting files as CI artifacts.

By the ScreenshotNeo team30 September 202610 min read

How to Take Screenshots with Selenium WebDriver and PHPUnit

Use the PHP Selenium client php-webdriver/php-webdriver. Save the current browser view with $driver->takeScreenshot('screenshot.png'); call it with no path to keep the PNG data in memory. For screenshots after a PHPUnit failure, capture while the WebDriver session is still alive, before tearDown() releases it. PHPUnit does not provide a built-in Selenium screenshot-on-failure switch in current versions: handle a failure in the test, or build a version-matched PHPUnit extension.

This guide covers direct page and element capture, failure handling, file and CI artifacts, common errors, and the tradeoffs between a local test hook and reusable integration. The examples are patterns to adapt to your pinned PHP, PHPUnit, php-webdriver, Selenium Server, browser, and driver versions; the source documentation does not establish one compatible version matrix.

1. Install the PHP WebDriver client

Install the PHP binding through Composer. A Selenium Server and a browser with a matching driver must also be available; the PHP package is the client, not the browser or server. Start the server using the instructions for the Selenium and browser versions you selected, then point the client at its WebDriver endpoint. Check the php-webdriver project wiki and PHPUnit documentation for the API and lifecycle details.

composer require php-webdriver/php-webdriver
composer require --dev phpunit/phpunit

Pin dependency versions in composer.lock and record the Selenium Server, browser, and driver versions in your project or CI configuration. PHPUnit’s current manual describes per-test setUp() and tearDown() lifecycle methods, but that alone does not guarantee compatibility among those independently versioned components.

2. Save a page screenshot

Once a RemoteWebDriver session exists and has navigated to a page, call takeScreenshot(). Provide a writable .png path to save the file directly. Omit the argument when you want the PNG data in a variable.

A PHPUnit test drives the browser, then php-webdriver saves the current view as a PNG artifact.
A PHPUnit test drives the browser, then php-webdriver saves the current view as a PNG artifact.
<?php
require __DIR__ . '/vendor/autoload.php';

use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

$driver = RemoteWebDriver::create(
    'http://localhost:4444',
    DesiredCapabilities::chrome()
);

try {
    $driver->get('https://example.com');

    if (!is_dir(__DIR__ . '/artifacts')) {
        mkdir(__DIR__ . '/artifacts', 0775, true);
    }
    $driver->takeScreenshot(__DIR__ . '/artifacts/page.png');

    // Or retain PNG bytes and decide where to write them later.
    $pngData = $driver->takeScreenshot();
    file_put_contents(__DIR__ . '/artifacts/page-copy.png', $pngData);
} finally {
    $driver->quit();
}

The package describes this as a current-page screenshot helper. Treat the default scope as the browser’s current view unless the specific browser and driver combination documents and verifies broader capture. Selenium’s Java TakesScreenshot documentation cautions that behavior can be best effort on implementations that do not conform to the WebDriver standard; it is a reason to check your actual stack, not a guarantee about every PHP binding. See the Selenium TakesScreenshot API.

3. Capture one element

When the question is about a component rather than the full browser view, locate it and call takeElementScreenshot(). This avoids saving unrelated page content. The element must be present and suitable for capture at that moment; wait for it when the page renders asynchronously.

<?php
use Facebook\WebDriver\WebDriverBy;

$driver->get('https://example.com');
$element = $driver->findElement(WebDriverBy::id('some_id'));
$element->takeElementScreenshot(__DIR__ . '/artifacts/component.png');

Use a selector that is stable in your application. If a lookup fails, first check whether the page has loaded the relevant component and whether the identifier is still present. A successful page screenshot does not imply that an element lookup will succeed.

4. Capture a screenshot when a PHPUnit test fails

The key constraint is browser-session lifetime. PHPUnit calls setUp() and tearDown() for each test method, and teardown is where projects commonly close the driver. Capture before releasing the session. The following test-case pattern catches a thrown failure, saves a uniquely named image, rethrows the original failure, and quits the browser in a finally block. Adapt the driver endpoint and browser capability to your environment.

Failure capture must happen while the WebDriver session is still available.
Failure capture must happen while the WebDriver session is still available.
<?php
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use PHPUnit\Framework\TestCase;

final class CheckoutTest extends TestCase
{
    private ?RemoteWebDriver $driver = null;

    protected function setUp(): void
    {
        $this->driver = RemoteWebDriver::create(
            'http://localhost:4444',
            DesiredCapabilities::chrome()
        );
    }

    public function testCheckoutPage(): void
    {
        $artifactDir = __DIR__ . '/artifacts';
        if (!is_dir($artifactDir)) {
            mkdir($artifactDir, 0775, true);
        }

        try {
            $this->driver->get('https://example.com/checkout');
            // Replace with an assertion relevant to the application.
            self::assertSame('Checkout', $this->driver->getTitle());
        } catch (\Throwable $failure) {
            if ($this->driver !== null) {
                $file = sprintf(
                    '%s/%s-%s.png',
                    $artifactDir,
                    preg_replace('/[^A-Za-z0-9_.-]/', '_', $this->name()),
                    bin2hex(random_bytes(4))
                );
                try {
                    $this->driver->takeScreenshot($file);
                    fwrite(STDERR, "Saved failure screenshot: {$file}" . PHP_EOL);
                } catch (\Throwable $captureError) {
                    fwrite(STDERR, "Screenshot capture failed: {$captureError->getMessage()}" . PHP_EOL);
                }
            }
            throw $failure;
        }
    }

    protected function tearDown(): void
    {
        if ($this->driver !== null) {
            $this->driver->quit();
            $this->driver = null;
        }
    }
}

This local try/catch catches assertion exceptions and other thrown errors raised inside that block. It does not catch failures that occur before the block, such as a failure in setUp(), nor does it capture every possible runner outcome automatically. The nested catch keeps a screenshot problem from replacing the original test failure. The test still rethrows the original exception so PHPUnit reports the failure normally.

Keep the browser alive through capture. Do not call quit() in the catch path before taking the screenshot, and avoid closing the session in a helper called by the failing assertion. If the failure is a lost browser session, capture may itself be impossible; preserve the original failure details and report capture failure separately.

5. Choose local handling or a reusable PHPUnit extension

Approach Scope and coverage Tradeoffs
Try/catch around test work One test or shared project helper; handles thrown failures inside its guarded block. Simple to reason about, but every relevant path must use the wrapper. Setup failures and outcomes outside the block need separate handling.
PHPUnit runner extension and outcome subscriber Reusable suite-level integration that can subscribe to failure or error outcomes. Requires wiring the active WebDriver session into the extension and adapting event APIs to the installed PHPUnit version. It is an implementation pattern, not a built-in Selenium feature.

For a suite-wide solution, implement and register a PHPUnit test-runner extension and subscribe to the outcome events supported by your PHPUnit release. The extension must be able to identify the driver belonging to the failed test while that driver is still alive. Design ownership explicitly: for example, a project-managed session registry can associate a test identifier with a driver, while the test lifecycle remains responsible for releasing it. Verify event names, interfaces, and registration against the manual for the exact PHPUnit version in the PHPUnit 12.5 documentation or the version you actually use. The documented extension mechanism does not supply a ready-made integration for this PHP Selenium client.

Do not copy $captureScreenshotOnFailure, $screenshotPath, or $screenshotUrl from old Selenium extension examples as if they were current PHPUnit settings. Those options belong to legacy extension-era material, not a general current PHPUnit switch. A migration should replace that old configuration with project-owned failure handling or a version-matched extension.

6. Store, name, and retain artifacts

Use a project-relative or explicitly configured artifact directory, ensure it exists, and check that the test process can write to it. Use unique names: parallel tests can otherwise overwrite a shared failure.png. Include a sanitized test name and a random suffix, as above; adding a CI run identifier can help associate files with a job. Avoid putting secrets or sensitive query data into filenames.

In remote execution, distinguish the PHP runner’s filesystem from the Selenium or browser host. The reviewed API descriptions do not settle filesystem behavior for every remote deployment. Confirm where the binding writes the screenshot in your specific topology, then configure your CI artifact upload and retention separately. Creating a local file does not automatically make it available in a hosted CI job’s artifact viewer.

  • Directory: create it before capture and grant the test user write permission.
  • Collisions: make names unique across test cases, retries, and parallel workers.
  • Retention: upload the directory as a CI artifact and choose retention under your CI policy.
  • Privacy: pages may display user data or tokens; restrict artifact access and redact sensitive content where appropriate.
  • Failure path: report the screenshot path in test output so a developer can locate it.

7. Performance, reliability, and cost

Capturing and writing an image adds browser-command and filesystem work to a test. Capture only on failures when the goal is diagnosis; always-on screenshots add time and storage to successful runs. For flaky failures, consider whether a single failure-time image is enough to distinguish a rendering issue from a timing issue. A screenshot records visual state, but it does not replace logs, DOM state, browser console output, or network diagnostics.

Reliability depends on the full chain: the browser session remains active, the page is in a useful state, the WebDriver command succeeds, the target path is writable, and CI retains the resulting file. A failure in any link can leave no artifact. Keep screenshot errors secondary to the original test error, as in the example, and log both. On remote grids, check the exact session and file behavior rather than assuming the PHP worker and browser share a disk.

There is no source-backed benchmark or cost figure for the time and storage overhead of these screenshots. Measure in your own CI environment, especially with parallel workers and retry policies. Bound artifact retention and capture frequency to keep storage manageable.

8. Troubleshooting

Symptom Likely cause Fix
No PNG appears Output directory is missing or not writable, or capture threw before writing. Create the directory, check permissions as the CI user, catch and log capture exceptions, and verify the reported path.
Screenshot command fails after assertion The browser was closed, the session expired, or the browser crashed. Capture before teardown or quit(); keep the failure handler inside the session lifetime. If the session is already lost, preserve logs and report the capture error without masking the assertion.
Element screenshot says element not found The selector is wrong or the component has not rendered yet. Check the selector against the current DOM and wait for the application’s render condition before locating the element.
Image shows only the visible browser area Capture scope can depend on implementation and driver behavior. Treat it as the current view by default. Verify full-page behavior for your exact browser/driver stack or use a separately documented full-page mechanism.
Works locally but not in CI Different browser/driver versions, endpoint configuration, headless environment, permissions, or artifact upload rules. Pin and print component versions, confirm the WebDriver endpoint, test path permissions under the CI account, and configure artifact collection.
Failure is reported but no screenshot The local catch did not surround the failing operation, failure occurred in setup, or the session was unavailable. Expand guarded scope where appropriate, handle setup separately, or add a version-matched runner extension with access to the live session.
Old configuration has no effect Legacy PHPUnit Selenium extension settings were mistaken for current PHPUnit behavior. Remove reliance on those properties and implement test-level capture or a compatible PHPUnit extension.

9. Or skip the browser setup

If your goal is a screenshot of a URL rather than a Selenium-driven interaction, ScreenshotNeo provides a one-request screenshot API. It is useful when you do not need to retain a live browser session or write browser setup for that capture. See the ScreenshotNeo API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server gives AI agents tools to take screenshots, inspect page information, and capture PDFs. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000. The stated plans are Starter $5/3,000, Growth $15/15,000, Pro $39/60,000, Scale $99/250,000, and Business $249/1,000,000 per month; annual billing gives two months free, and every feature is available on every plan. See the docs for the other capture and delivery options.

Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.

10. FAQ

Can I keep the screenshot in memory?

Yes. Call $driver->takeScreenshot() without a save path to get PNG data, then write or process that data yourself.

Does PHPUnit capture a screenshot automatically on every failure?

Do not assume so. Current PHPUnit offers extension mechanisms, but a Selenium screenshot integration must be implemented and connected to the live driver for your version.

Can Selenium capture a full page?

Do not assume the default call captures beyond the current browser view. Behavior depends on the browser and driver implementation; verify the exact combination you run.

Should I use an element or page screenshot?

Use an element screenshot when you need a focused component image and a page screenshot when surrounding layout is relevant. Both depend on the page being in the expected state at capture time.

Where does a screenshot from a remote Selenium session go?

Confirm this in your deployment. Remote execution can involve distinct PHP runner and browser hosts, and the destination and artifact handling must be checked for the specific setup.

Sources and version fit

Before adopting the snippets, compare their signatures and lifecycle integration with the exact package versions in your project. The references establish the APIs and patterns above, not a universal compatibility matrix.