Getting Started

Now that you understand what Playwright is and why it's so powerful, let's dive into how to set it up and write your first automated script.

Install Playwright

To use Playwright, you need Node.js installed on your computer. If you don't have Node.js, you can download it here.

Once Node.js is ready:

1. Open your terminal or command prompt.

2. Run this command to create a new project:

mkdir playwright-demo && cd playwright-demo npm init -y

This sets up a new folder with a basic Node.js project.

3. Install Playwright using this command:

npm install playwright

That's it! You now have Playwright installed.

Set Up Your First Script

Let's write a simple script to open a browser and visit a website.

1. Create a new file called example.js:

touch example.js

2. Open example.js in your favorite code editor (like VS Code) and paste this code:

Javascript
Copy
const { chromium } = require('playwright');

(async () => {
    // Launch a browser
    const browser = await chromium.launch({ headless: false });
    
    // Open a new page
    const page = await browser.newPage();
    
    // Navigate to a website
    await page.goto('https://example.com');
    
    // Take a screenshot
    await page.screenshot({ path: 'screenshot.png' });

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

3. Save the file.

Run the Script

In the terminal, run the script using:

node example.js

What happens:

  • A browser window will open.
  • It will visit example.com.
  • A screenshot of the page will be saved as screenshot.png in your project folder.

Understanding the Code

Let's break the code into smaller parts:

1. Launching the Browser:

Javascript
Copy
const browser = await chromium.launch({ headless: false });
  • chromium.launch() starts the Chromium browser.
  • { headless: false } means the browser will be visible. Set it to true to run in the background (headless mode).

2. Creating a New Page:

Javascript
Copy
const page = await browser.newPage();

This opens a new tab in the browser.

3. Navigating to a Website:

Javascript
Copy
await page.goto('https://example.com');

The goto method takes you to the specified URL.

4. Taking a Screenshot:

Javascript
Copy
await page.screenshot({ path: 'screenshot.png' });

Saves a screenshot of the current page to your project folder.

5. Closing the Browser:

Javascript
Copy
await browser.close();

Closes the browser when the script is done.

Explore Other Browsers

Playwright supports other browsers too! You can replace chromium with firefox or webkit in your script to test on those browsers.

Example for Firefox:

Javascript
Copy
const { firefox } = require('playwright');
const browser = await firefox.launch({ headless: false });