Build a Headless Code Browser in Python
In this article
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
- Install Playwright. Open a terminal and run:
pip install playwright. This installs the Python library. - 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. - Create a new Python file. Name it something like
headless_browser.pyand open it in your editor. - 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. - Write the main function. Start with a function that launches the browser, opens a new page, and navigates to a URL. Example:
Thedef 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()wait_until="networkidle"ensures the page has finished loading most resources, which is important for JavaScript-heavy sites. - Extract code blocks. Use Playwright's locator to find code elements. For example, to get all
<pre>or<code>elements:
If the site uses a specific class likecode_elements = page.locator("pre, code").all_text_contents() for code in code_elements: print(code).highlightor.code-block, adjust the selector accordingly. - 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# ---. - Handle dynamic content. If the code appears after a click or scroll, use
page.click()orpage.evaluate("window.scrollTo(0, document.body.scrollHeight)")before extracting. Addpage.wait_for_timeout(1000)to allow time for rendering. - 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 playwrightis not enough; you must also runplaywright 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. Usenetworkidleor 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, callhtml = page.content()and parse it with BeautifulSoup if needed.
Troubleshooting
- Error: "Executable doesn't exist" — You haven't installed the browser. Run
playwright install chromiumagain 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=Falsetemporarily 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 ofnetworkidlefor 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.