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("http://scrapfly.io/")

# to stop browser on notebook close we can add a shutdown hook:
def shutdown_playwright():
    await browser.close()
    await pw.stop()
import atexit
atexit.register(shutdown_playwright())

Provided by Scrapfly

This knowledgebase is provided by Scrapfly — a web scraping API that allows you to scrape any website without getting blocked and implements a dozens of other web scraping conveniences. Check us out 👇