How to load local files in Playwright?

To open a local HTML file in Playwright, convert the file path to a file:// URL and pass it to page.goto(). Python's pathlib.Path can resolve the full path and convert it to a valid file URI.

Before running the examples, install Playwright and the Chromium browser:

python3 -m pip install playwright
python3 -m playwright install chromium

Open a Local HTML File in Playwright

Create a file named test.html:

<!DOCTYPE html>
<html>
<head>
    <title>Local Playwright Test</title>
</head>
<body>
    <h1>Hello from a local file</h1>
</body>
</html>

Next, create demo.py in the same directory as test.html:

from pathlib import Path
from playwright.sync_api import sync_playwright

file_url = Path("test.html").resolve().as_uri()

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto(file_url)
    print(page.locator("h1").text_content())
    browser.close()

Path("test.html") refers to test.html relative to the directory where you run the Python script. Save test.html and demo.py in the same directory, then run the command from that directory.

Run the script with:

python3 demo.py

Output:

Hello from a local file

Path.resolve() converts the relative path to an absolute path, while as_uri() converts that absolute path to a valid file:// URL.

Open a Local HTML File with a Direct Path

If you already know the complete file:// URI, you can pass it directly to page.goto().

For example, on Linux, this path:

/home/user/Desktop/playwright-demo/test.html

corresponds to:

file:///home/user/Desktop/playwright-demo/test.html

Use it directly:

page.goto("file:///home/user/Desktop/playwright-demo/test.html")

On Windows, a path such as:

C:\Users\name\test.html

corresponds to:

file:///C:/Users/name/test.html

Path.as_uri() is usually safer because it handles platform-specific URI formatting automatically.

Related Playwright web scraping questions: