Introduction to Playwright for Browser Automation

Jul 12, 2024

Introduction to Playwright for Browser Automation

Overview

  • Speaker: Victor
  • Duration: 15 minutes
  • Purpose: Introduction to Playwright, an automation tool
  • Topics Covered:
    • What Playwright is
    • Installation process
    • Generating automation scripts without code
    • Interacting with UI elements
    • Taking screenshots and recording videos

What is Playwright?

  • Node.js library for browser automation
  • Open-source and backed by Microsoft
  • Developed by former Puppeteer team members from Google
  • Responsive support:
    • Triage time of < 48 hours
    • Addressed 1600+ issues
  • Supported Browsers:
    • Google Chrome, Microsoft Edge, Apple Safari, Opera, Mozilla Firefox
  • Supported Languages:
    • Typescript, JavaScript, C#, Java, Python
  • Features/PERKS:
    • Automatic browser downloads
    • Video recording of tests
    • Network request interception/modification
    • Device, location, locale, timezone emulation
    • Code Generator and Debugger

Installation Process

  1. Prerequisites: Node.js, Playwright, code editor (e.g., Visual Studio Code)
  2. Node.js Installation:
  • Visit Nodejs.org
  • Download and install the LTS version
  1. Visual Studio Code Installation:
  1. Setting up the Project:
  • Create a new folder (e.g., playwright-test)
  • Open folder in Visual Studio Code
  • Install Playwright in terminal with npm i -D playwright

Creating Automation Scripts

  • New File: hello-playwright.js
  • Playwright Inspector:
    • Command: npx playwright codegen
    • Provides a browser window and code inspector
    • Records actions and generates corresponding code
    • Supports languages: JavaScript, Java, Python, async Python, C#

Code Structure

  1. Browser Initialization:
  • Starts a new browser window
  1. Context Initialization:
  • Starts a new independent window within the browser
  1. Page Actions:
  • Navigates to websites, clicks links, and performs actions

Running the Script

  • Command: node hello-playwright.js
  • Modifications:
    • Take a screenshot: page.screenshot({ path: 'wiki_screen.png' })
    • Record a video:
      const context = await browser.newContext({
        recordVideo: { dir: 'videos' }
      });
      
    • Headless Mode: By default, runs headlessly

Conclusion

  • Encouragement to comment about Playwright usage
  • Newsletter: Visit testopic.com/playwright for updates, cheatsheets, and more