How to Capture .PNG using Playwright & 0Browser, a Headless Browser as a Service

How to Capture PNG using Playwright

In this example we will learn how to capture a .PNG screen shot of Y-Combinator news page using JavaScript, Playwright and 0Browser. This example is very similar to the Capture PNG using Puppeteer example but we will use Playwright. Playwright Node library is an attempt by Microsoft which provides one API that works with multiple headless browsers such as Chromium, WebKit and Firefox.

Prerequisites

Make sure you have Node.js installed and Playwright added.

> npm install playwright
Also keep your 0Browser Account API Key handy.
If something doesn't add up here, please check out the 0Browser Getting Started guide for all details on this.

Setup

Now that we have the prerequisites in order, let's get to the fun part!

Use your favorite IDE to create a new JS file called index-playwright.js.
Following code snippet shows how to connect to 0Browser proxy to navigate to the y-combinator news page and capture a .PNG screen-shot.

const pw = require('playwright');

(async () => {    
    const browser = await pw.chromium.connect({
        wsEndpoint: 
        'wss://proxy.0browser.com?token={YOUR-API-KEY}&timeout=60000',
    });
    const context = await browser.newContext();
    const page = await context.newPage();

    await page.goto('https://news.ycombinator.com');
    await page.screenshot({ path: 'ycombinator.png' });

    await browser.close();
})();

Find this source code on Github

Run

Use NodeJS to run the script using below command.

 > node index-playwright.js

Then you will find a new file called ycombinator.png in the same directory as index-playwright.js script lives.
Thats it, Great job!


...
0Browser