User Agents

Web browsers and everyday web tech, explained

Build a Headless Code Browser in Python

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to build a headless code browser in Python — a script that fetches, renders, and extracts code from web pages without opening a visible browser window. You'll use Playwright to control a headless Chromium instance, navigate to pages, wait for JavaScript to execute, and pull out code blocks or full page source. This is useful for scraping documentation, collecting code snippets, or testing your own site's rendered output.

What You'll Need

  • Python 3.7 or newer installed on your system.
  • Basic familiarity with the command line and Python syntax.
  • An internet connection to download packages and browse pages.

Step-by-Step

  1. Install Playwright. Open a terminal and run: pip install playwright. This installs the Python library.
  2. Install the browser binaries. Run playwright install chromium. This downloads the Chromium browser that Playwright will control. If you skip this, you'll get an error when trying to launch the browser.
  3. Create a new Python file. Name it something like headless_browser.py and open it in your editor.
  4. Import the sync API. At the top of your file, add: from playwright.sync_api import sync_playwright. The sync API is easier for straightforward scripts; use the async version if you're building a larger concurrent application.
  5. Write the main function. Start with a function that launches the browser, opens a new page, and navigates to a URL. Example:
    def fetch_code(url):
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            page = browser.new_page()
            page.goto(url, wait_until="networkidle")
            # your extraction logic here
            browser.close()
    The wait_until="networkidle" ensures the page has finished loading most resources, which is important for JavaScript-heavy sites.
  6. Extract code blocks. Use Playwright's locator to find code elements. For example, to get all <pre> or <code> elements:
    code_elements = page.locator("pre, code").all_text_contents()
    for code in code_elements:
        print(code)
    If the site uses a specific class like .highlight or .code-block, adjust the selector accordingly.
  7. Save the output. Instead of printing, write the extracted code to a file. Use with open("output.txt", "w") as f: and write each code block separated by a delimiter like # ---.
  8. Handle dynamic content. If the code appears after a click or scroll, use page.click() or page.evaluate("window.scrollTo(0, document.body.scrollHeight)") before extracting. Add page.wait_for_timeout(1000) to allow time for rendering.
  9. Run the script. Execute your file with python headless_browser.py. Test it with a simple URL like a GitHub repository's raw code page or a documentation site.

Common Mistakes

  • Forgetting to install the browser. Running pip install playwright is not enough; you must also run playwright install chromium.
  • Using the wrong selector. Many sites nest code inside multiple divs. Inspect the page with your regular browser's developer tools to find the actual element.
  • Not waiting for JavaScript. If you use wait_until="domcontentloaded", you might miss content that loads later. Use networkidle or explicit waits.
  • Blocking on popups or dialogs. Some pages show cookie banners or modals. You can dismiss them with page.click("button:has-text('Accept')") or similar, but be careful with selectors.

Tips

  • Use a user agent. Some sites block headless browsers. Set a realistic user agent: page.set_extra_http_headers({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}).
  • Add a timeout. Set page.set_default_timeout(30000) to avoid hanging on slow pages.
  • Take a screenshot for debugging. If extraction fails, save a screenshot: page.screenshot(path="debug.png") to see what the page actually looks like.
  • Use page.content() for full HTML. If you just need the rendered HTML, call html = page.content() and parse it with BeautifulSoup if needed.

Troubleshooting

  • Error: "Executable doesn't exist" — You haven't installed the browser. Run playwright install chromium again and ensure it completes without errors.
  • Page loads blank or empty. The site might block headless browsers. Try adding a user agent, or use headless=False temporarily to see if the page loads in a visible window. If it does, the issue is detection.
  • Code blocks are empty. The selector might be wrong. Use page.locator("pre").count() to see how many elements match. If zero, inspect the page's HTML structure.
  • Script hangs forever. Increase timeout or use wait_until="domcontentloaded" instead of networkidle for pages with endless loading (like infinite scroll).
  • Permission errors when saving files. Ensure the output directory exists and is writable. Use absolute paths to avoid confusion.

Frequently Asked Questions

Can I use Selenium instead of Playwright?

Yes, but Playwright is generally faster and has a simpler API for headless mode. Selenium requires a separate WebDriver and often more configuration.

Does this work on any website?

Most sites work, but some use anti-bot measures that block headless browsers. You may need to add stealth techniques, but that's beyond this guide's scope.

Can I extract code from multiple pages?

Yes, loop over a list of URLs and call your fetch function for each. Be polite and add a small delay between requests to avoid overwhelming the server.

How do I get the code as plain text without HTML tags?

Use all_text_contents() which returns the visible text inside the element, stripping tags. If you need the raw HTML, use inner_html() instead.

Is it legal to scrape code from websites?

Check the website's terms of service and robots.txt. Scraping public data for personal use is generally acceptable, but redistributing or commercial use may violate terms.

What if the code is inside an iframe?

You need to switch to the iframe first. Use frame = page.frame_locator("iframe") and then query within that frame.