Why isn't sync_playwright() working in my Playwright Python setup, and why am I getting the error 'playwright is not defined'?

I’m using Playwright with Python on Windows 10 (version 1.21.1) to automate web testing. I attempted to use the sync_playwright() method to simplify writing synchronous scripts, but I keep receiving an error saying ‘playwright is not defined’.

I followed examples from the Playwright documentation and expected the browser to launch successfully, but the script fails before that happens. It seems like Playwright isn’t being recognized correctly in the script.

Has anyone experienced this issue before or knows how to properly configure and use sync_playwright() in Python? Any working examples or suggestions would be very helpful.

This is a common issue when working with Playwright’s synchronous API. The error ‘playwright is not defined’ usually happens because the required module wasn’t imported correctly.

To use sync_playwright(), you must import it from playwright.sync_api. The function also needs to be used within a with context manager so Playwright can properly manage browser processes.

Here is a working example:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("http://example.com")
    print(page.title())
    browser.close()

This script launches a Chromium browser, opens a page, navigates to a website, prints the page title, and then closes the browser.

Make sure that:

You correctly import sync_playwright

You use it inside a with block

Playwright is properly installed in your environment

Checking these usually resolves the error.

I ran into a similar issue before, and in my case the problem was related to the Python environment configuration rather than the code itself.

Playwright relies on certain dependencies and browser binaries. If your environment is not properly configured, functions like sync_playwright() may fail or behave unexpectedly.

A reliable approach is to create a clean virtual environment and reinstall Playwright.

Example setup:

Create a virtual environment

python -m venv playwright-env

Activate the environment

Windows

.\playwright-env\Scripts\activate

Install Playwright

pip install playwright

Install required browser binaries

playwright install

Using an isolated environment helps avoid conflicts with other installed packages and ensures Playwright dependencies are installed correctly.

After completing these steps, try running your script again and see if the sync_playwright() method works properly.