Articles

Getting Started with Playwright in Python

2024-08-15·3 min read
Photo by Hitesh Choudhary on Unsplash

In the realm of web application development, ensuring that your application works flawlessly across different browsers is no small feat. With ever-evolving standards and a myriad of devices accessing the web, developers struggle to keep up. Enter Playwright—an open-source automation library from Microsoft, capable of handling modern web testing with ease. This article provides a laid-back, easy-going guide to getting started with Playwright in Python.

What is Playwright?

Playwright is an open-source library designed to automate web browsers through a single API. With support for major web browsers like Chrome, Firefox, and Safari, it allows developers to perform end-to-end tests across various platforms seamlessly. In simple terms, Playwright enables automated interaction with web apps, which can be used for automated testing, scraping, and much more.

Photo by NordWood Themes on Unsplash

Why Choose Playwright?

While there are several browser automation tools available, Playwright stands out for several reasons:

Getting Started

Let's walk through the steps to get started with Playwright using Python. Assume you have Python installed on your system.

Step 1: Setting Up Your Environment

Start by creating a virtual environment to keep your dependencies isolated:

python -m venv myenv
source myenv/bin/activate   # On Windows use `myenv\Scripts\activate`

Next, you'll need to install Playwright along with its dependencies:

pip install playwright
python -m playwright install

Step 2: Writing Your First Script

Let’s create a basic script to navigate to a website, take a screenshot, and close the browser.

Create a file named test_script.py and add the following code:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://example.com")
    page.screenshot(path="example.png")
    browser.close()
    
with sync_playwright() as playwright:
    run(playwright)

Step 3: Running Your Script

To run the script, simply use the Python command:

python test_script.py

This script does the following:

  1. Launches a Chromium browser in non-headless mode.
  2. Creates a new page.
  3. Navigates to https://example.com.
  4. Takes a screenshot and saves it as example.png.
  5. Closes the browser.

Explore More Commands

Playwright supports many actions you can perform on web pages. Let’s explore some common tasks you may need.

Interactions with web elements are a cornerstone of web automation. Below is an example of logging into a website:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://example-login.com")
    
    page.fill('input[name="username"]','myusername')
    page.fill('input[name="password"]','mypassword')
    page.click('button[type="submit"]')
    
    page.screenshot(path="loggedin.png")
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

This script will:

  1. Navigate to a login page.
  2. Fill in the username and password fields.
  3. Click the login button.
  4. Take a screenshot after the login attempt.

Handling Network Requests

Intercepting network requests can be useful for various testing scenarios. Here’s how you can mock a network request:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    
    def handle_request(route, request):
        if 'api/data' in request.url:
            route.fulfill(status=200, body='{"key":"value"}', headers={'Content-Type': 'application/json'})
        else:
            route.continue_()

    page.route("**", handle_request)
    page.goto("https://example.com")
    
    # Code to interact with the page
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

This script will:

  1. Intercept all network requests.
  2. Mock the response for requests containing api/data.

Tips for Writing Effective Tests

  1. Use Auto-Wait: Take advantage of Playwright’s auto-wait features. It waits for elements to be actionable before performing operations, which reduces flakiness.
  2. Isolate Tests: Use different browser contexts to isolate tests and avoid shared state.
  3. Leverage Assertions: Spices up your tests with proper assertions to ensure expected outcomes.

Conclusion

Playwright is a powerful tool designed to simplify the complexities of web automation and testing. Its ease of use and robust features make it an excellent choice for developers looking to ensure their web applications function flawlessly across multiple browsers and devices. With the steps outlined above, you should now have a solid foundation to start leveraging Playwright in Python.

Ready to dive deeper? Explore the official Playwright documentation for more advanced features and use-cases. Happy testing!

Report bugs like it's 2024
Bug reports has looked the same since forever. You try to jam as much detail as possible to avoid the dreaded "can't reproduce". It's time to fix that. Whitespace captures every possible detail automatically and puts it all in a neat little package you can share as link.

Read more

Getting Started with Puppeteer in C#

Web scraping—or extraction—is a critical tool in modern web development, used in gathering data from different web sources. Read more

Published 5 min read
Getting Started with Puppeteer in Java

Automation testing has become an integral part of the development ecosystem. Read more

Published 3 min read
Getting Started with Puppeteer in JavaScript

As a developer, you’ve probably had moments where you needed to automate repetitive browser tasks, like scraping web data, generating screenshots, or testing web applications. Read more

Published 4 min read
Getting Started with Puppeteer in Node.js

Modern web development often requires testing and automating various web applications and processes. Read more

Published 3 min read
Getting Started with Playwright in PHP

In the fast-paced world of web development, testing is essential to ensure the stability and functionality of applications. Read more

Published 3 min read
Getting Started with Playwright in C#

In the fast-evolving world of web development, you need reliable tools for your end-to-end testing to ensure your applications run smoothly across different browsers and environments. Read more

Published 3 min read
Getting Started with Playwright in Java

Modern web development can sometimes feel like a whirlwind of continuous updates and new tools. Read more

Published 5 min read
Getting Started with Playwright in JavaScript

Development and testing can often feel like taming a herd of wild animals. Read more

Published 4 min read
Getting Started with Playwright in Node.js

In the world of web development, automated browser testing can be a complex yet essential task. Read more

Published 3 min read
Getting started with Selenium in C#

In today's fast-paced development environment, ensuring that web applications are functioning correctly is crucial. Read more

Published 4 min read
One-click bug reports straight from your browser
Built and hosted in EU 🇪🇺