Why does sync_playwright().start() hang in my Python script, and how can I fix it?

I’m trying to use Playwright in Python with the synchronous API. My script looks like this:

from playwright.sync_api import sync_playwright

print("debug1")
p = sync_playwright().start()
print("debug2")
browser = p.firefox.launch(headless=False)
page = browser.new_page()
page.goto("http://whatsmyuseragent.org/")
page.screenshot(path="example.png")
browser.close()

The program prints debug1 but then hangs indefinitely on sync_playwright().start(). I’ve tried switching browsers and using headless mode, but the issue persists.

Playwright requires its browser binaries to be installed. If they’re missing, sync_playwright().start() can hang. Run:

python -m playwright install

This installs Chromium, Firefox, and WebKit. After this, try running your script again.

The recommended way is to use sync_playwright() as a context manager, which avoids hanging issues:

from playwright.sync_api import sync_playwright

print(“debug1”) with sync_playwright() as p: print(“debug2”) browser = p.firefox.launch(headless=False) page = browser.new_page() page.goto(“http://whatsmyuseragent.org/”) page.screenshot(path=“example.png”) browser.close()

This ensures proper startup and teardown of Playwright.

Sometimes hanging occurs due to missing dependencies or incompatible Python environments:

Make sure you’re using Python ≥3.7.

If on Linux, ensure required libraries are installed (e.g., libnss3, libatk1.0-0, libxss1, libgtk-3-0).

Try running in a clean virtual environment:

python -m venv venv source venv/bin/activate # Linux/macOS venv\Scripts\activate # Windows pip install playwright python -m playwright install

Then run your script inside this environment.

These three solutions usually resolve hanging issues with sync_playwright().start().