ModuleNotFoundError
ModuleNotFoundError: No module named 'playwright'
Stack trace
Traceback (most recent call last):
File "app.py", line 3, in <module>
from playwright.sync_api import sync_playwright
ModuleNotFoundError: No module named 'playwright' Why it happens
The error happens because the playwright package is missing from your Python environment. Your code attempts to import playwright modules, but Python cannot find the package since it was never installed or the environment is incorrect.
Detection
You can detect this error early by running 'pip show playwright' or checking your environment's installed packages before running your script.
Causes & fixes
playwright package is not installed in the current Python environment
Run 'pip install playwright' in your environment to install the package before running your code.
Running the script in a different environment where playwright is not installed
Activate the correct virtual environment or container where playwright is installed before executing the script.
playwright installed but not properly initialized with 'playwright install' command
After installing the package, run 'playwright install' to download browser binaries required for automation.
Code: broken vs fixed
from playwright.sync_api import sync_playwright # This line triggers ModuleNotFoundError if playwright is missing
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://example.com')
print(page.title())
browser.close() import os
from playwright.sync_api import sync_playwright # Fixed: playwright installed and imported properly
# Ensure environment is set up with playwright installed
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://example.com')
print(page.title())
browser.close() Workaround
If you cannot install playwright immediately, catch the ModuleNotFoundError and provide a user-friendly message prompting installation.
Prevention
Use virtual environments and dependency management tools like requirements.txt or poetry.lock to ensure playwright is installed and consistent across deployments.