Calmcode - playwright: first demo

A first demo of Playwright in Python.

1 2 3 4 5 6 7 8 9

Install

You can install playwright with pip.

pip install --upgrade pip
pip install playwright

However, this will only install the Python dependencies. You'll also need to install headless browsers that playwright can interact with. These can be installed via:

playwright install

Demo

Given that everything is installed, let's give playwright a spin!

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    # Load the Chrome browser and see it
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://calmcode.io")
    # Grab the title
    print(page.title())
    # Make a screenshot
    page.screenshot(path="example.png")
    browser.close()

When you run this script, you'll see a browser open up. It's brief, just long enough for playwright to make a screenshot and then it closes. You can choose to run playwright without this browser popup by setting headless=True, which is the default setting.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    # Headless mode turned on
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto("https://calmcode.io")
    print(page.title())
    page.screenshot(path="example.png")
    browser.close()