The Pragmatic Programmer

Appian, Pega, Java, DevSecOps, Quality Engineering

Automating Browser Tasks with Playwright and TypeScript

When it comes to automating browser tasks and interactions, Playwright has emerged as a powerful tool in the developer’s toolkit. In this tutorial, we’ll explore how to use Playwright with TypeScript to automate tasks like navigating to websites and capturing screenshots.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  1. Node.js (which includes npm, the Node Package Manager)
  2. TypeScript (install globally using npm install -g typescript)

Getting Started

1. Project Setup

Create a new directory for your project and navigate to it using your terminal or command prompt.

mkdir playwright-tutorial
cd playwright-tutorial

2. Installing Playwright

In the project directory, install the Playwright library using npm:

npm install playwright

This will install the Playwright library along with its dependencies.

3. Writing the Script

Create a TypeScript file in the project directory. You can name it playwright_script.ts. Open this file in your favorite code editor and paste the following code:

import { chromium, Browser, Page } from 'playwright';

(async () => {
  // Launch the browser
  const browser: Browser = await chromium.launch();

  // Create a new browser context
  const context = await browser.newContext();

  // Create a new page
  const page: Page = await context.newPage();

  // Navigate to a website
  await page.goto('https://www.example.com');

  // Take a screenshot
  await page.screenshot({ path: 'screenshot.png' });

  // Close the browser
  await browser.close();
})();

4. Compiling and Running the Script

To compile the TypeScript code into JavaScript, run the following command in the terminal:

tsc playwright_script.ts

This will generate a playwright_script.js file in the same directory.

Now, run the compiled script using Node.js:

node playwright_script.js

After running the script, you should see a new screenshot file named screenshot.png in your project directory. This screenshot captures the webpage you navigated to.

Customization

Feel free to customize the script to suit your needs. You can change the URL to any website you want to automate, modify interaction steps, or capture additional data using Playwright’s rich API.

Conclusion

With Playwright and TypeScript, automating browser tasks becomes efficient and enjoyable. The combination of Playwright’s powerful capabilities and TypeScript’s static typing makes for robust and maintainable browser automation scripts.

Now that you’ve learned the basics, explore Playwright’s documentation to discover more advanced features and possibilities for automating web interactions.

Happy scripting!