How to run Playwright in Jupyter notebooks?

Playwright is a popular web browser automation library for Python which can be run in Jupyter notebooks for quick web scraping scripts. However, since Jupyter notebooks run its own asyncio loops we cannot start the synchronous playwright client:

# in Jupyter:
from playwright.sync_api import sync_playwright
playwright = sync_playwright().start()

Error: It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.

To use Playwright in Jupyter notebooks we should use the asynchronous client explicitly:

# in Jupyter
from playwright.async_api import async_playwright

pw = await async_playwright().start()
browser = await pw.chromium.launch(headless=False)
page = await browser.new_page()

# note all methods are async (use the "await" keyword)
await page.goto("")

# to stop browser on notebook close we can add a shutdown hook:
def shutdown_playwright():
    await browser.close()
    await pw.stop()
import atexit
Question tagged: Playwright, Jupyter

Related Posts

How to Scrape Google Maps

We'll take a look at to find businesses through Google Maps search system and how to scrape their details using either Selenium, Playwright or ScrapFly's javascript rendering feature - all of that in Python.

How to Scrape Dynamic Websites Using Headless Web Browsers

Introduction to using web automation tools such as Puppeteer, Playwright, Selenium and ScrapFly to render dynamic websites for web scraping