Playwright 1.20.1 and Typescript

Playwright is a headless cross-browser tester from the folks behind Puppeteer. I'm pulling some data together by scraping a few sites and wanted to see what Playwright had to offer. Here's a quick post on how to get setup quickly and pull data from the example.com test website.

Creating a workspace and installing Playwright

Create a folder and initialise a package.json with default settings:

mkdir playground
npm init -y

Add Playwright as a dependency:

npm i playwright@latest

I never want to think about compiling, debug map files, dist/out folders and all the rest of the bits that comes with Typescript for a quick project. Thankfully some smarter people than me have written the battle hardened ts-node project which compiles and runs Typescript projects out of the box for us.

I go with the convention npm run dev for running locally so I'm going to add that to the scripts in project.json.

The project.json looks like this:

{
  "name": "playground",
  "version": "1.0.0",
  "scripts": {
    "dev": "ts-node main.ts"
  },
  "devDependencies": {
    "ts-node": "^10.7.0"
  },
  "dependencies": {
    "playwright": "^1.20.1"
  }
}

Lets add a main.ts file now. This example write the contents of the the <title> tag from https://example.com into the console. It uses a top level await so we can drop into async/await.

import { chromium } from "playwright";

async function RunAsync(): Promise<void> {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto("https://example.com");
  const title = await page.innerHTML("title");
  await browser.close();
}

RunAsync().catch((e) => {
  throw e;
});

Putting it all together

Now we've got everything setup, we can run the main.ts script via ts-node by calling our custom dev script:

npm run dev

which outputs:

PS C:\test\playground> npm run dev

> playground@1.0.0 dev
> ts-node main.ts

Found title: Example Domain