How to Scrape With Headless Firefox
Discover how to use headless Firefox with Selenium, Playwright, and Puppeteer for web scraping, including practical examples for each library.
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())