Skip to content
Blog

Web Scraping Tools: Headless Browser Extraction with Playwright

How to build resilient headless browser web scraping tools for Google ADK agents using Playwright, HTML-to-Markdown conversion, and token optimization.

Published on • November 29, 2026

AI Assistant

While traditional HTTP scrapers (like requests or httpx with BeautifulSoup) are fast, they immediately fail on modern client-rendered single-page applications (SPAs) built with React, Vue, Angular, or Next.js. Furthermore, dynamic cookie banners, modal overlays, and infinite scrolling require a full JavaScript execution environment.

In this tutorial, we will construct an asynchronous web extraction tool for Google Agent Development Kit (ADK) using Microsoft Playwright. We’ll also implement DOM cleanup and HTML-to-Markdown distillation to ensure that extracted text fits cleanly within the LLM’s context window.


1. The Challenge of Raw Web Scraping for LLMs

Passing raw web pages to an LLM context creates several problems:

  1. Token Bloat: A typical corporate website contains 200 KB to 2 MB of HTML, 90% of which consists of CSS class definitions, SVG icons, inline scripts, and tracking pixels.
  2. Context Pollution: Navigation menus, footer legal notices, and cookie consent warnings distract the model from answering the user’s inquiry.
  3. Bot Mitigation & Hydration: SPAs display an empty <div id="root"></div> until JavaScript finishes executing.
+--------------------------------------------------------------+
|                         Target Web Page                      |
|                  (Dynamic React/Next.js App)                 |
+--------------------------------------------------------------+
                               |
                               v
+--------------------------------------------------------------+
|                    Playwright Headless Browser               |
|      - Waits for DOMContentLoaded / networkidle              |
|      - Strips <script>, <style>, <nav>, <footer>, <svg>      |
+--------------------------------------------------------------+
                               |
                               v
+--------------------------------------------------------------+
|                    Markdown Distillation                     |
|      - Converts clean semantic HTML into Markdown            |
|      - Truncates to max token/character budget               |
+--------------------------------------------------------------+
                               |
                               v
+--------------------------------------------------------------+
|                   Google ADK LlmAgent Context                |
|      - Compact, highly relevant semantic text                |
+--------------------------------------------------------------+

2. Installing Playwright and Dependencies

Install Playwright and browser binaries:

pip install playwright markdownify beautifulsoup4 google-adk
playwright install chromium --with-deps

3. Implementing the Playwright Extraction Tool

We write an async tool that launches a lightweight headless Chromium page, extracts the main content container, and transforms it into clean Markdown:

import re
from typing import Dict, Any, Optional
from bs4 import BeautifulSoup
from markdownify import markdownify as md
from pydantic import BaseModel, Field
from playwright.async_api import async_playwright
from google.adk.agents import Agent

class ScrapeWebPageInput(BaseModel):
    url: str = Field(description="The complete HTTP or HTTPS URL of the webpage to scrape.")
    css_selector: Optional[str] = Field(
        default=None,
        description="Optional CSS selector to isolate a specific article container (e.g., 'article', 'main', '#content')."
    )
    max_characters: int = Field(
        default=8000,
        ge=500,
        le=30000,
        description="Maximum characters of extracted Markdown to return."
    )

def clean_html_structure(raw_html: str, selector: Optional[str] = None) -> str:
    """Strips boilerplate tags and returns clean HTML."""
    soup = BeautifulSoup(raw_html, "html.parser")

    # Remove non-content tags
    for tag in soup(["script", "style", "nav", "footer", "header", "aside", "noscript", "svg", "form"]):
        tag.decompose()

    if selector:
        target = soup.select_one(selector)
        if target:
            return str(target)

    # Fallback to main content tags if present
    main_tag = soup.find("main") or soup.find("article")
    if main_tag:
        return str(main_tag)

    body = soup.find("body")
    return str(body) if body else str(soup)

async def scrape_web_page(input_data: ScrapeWebPageInput) -> Dict[str, Any]:
    """Navigates to a webpage using a headless browser, executes JS, and extracts text as Markdown."""
    async with async_playwright() as p:
        try:
            browser = await p.chromium.launch(
                headless=True,
                args=["--no-sandbox", "--disable-dev-shm-usage"]
            )
            context = await browser.new_context(
                user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
            )
            page = await context.new_page()

            # Navigate with a 20-second timeout
            response = await page.goto(
                input_data.url,
                wait_until="domcontentloaded",
                timeout=20000
            )

            # Wait briefly for dynamic hydration
            await page.wait_for_timeout(1000)

            title = await page.title()
            raw_html = await page.content()
            status_code = response.status if response else 200

            await browser.close()

            # Clean and convert HTML to markdown
            clean_html = clean_html_structure(raw_html, input_data.css_selector)
            markdown_content = md(clean_html, heading_style="ATX", strip=['a', 'img'])

            # Normalize excessive whitespace
            normalized_text = re.sub(r'\n{3,}', '\n\n', markdown_content).strip()

            is_truncated = len(normalized_text) > input_data.max_characters
            final_content = normalized_text[:input_data.max_characters]

            return {
                "status": "success",
                "http_status": status_code,
                "url": input_data.url,
                "title": title,
                "content_markdown": final_content,
                "is_truncated": is_truncated,
            }

        except Exception as exc:
            return {
                "status": "error",
                "url": input_data.url,
                "message": f"Browser navigation error: {str(exc)}"
            }

4. Configuring the Web Research Agent

We supply our Playwright tool to an ADK research agent:

research_agent = Agent(
    name="web_researcher",
    model="gemini-3.8-flash",
    instruction="""
    You are an automated technical research assistant.
    When asked to inspect online documentation, research technical articles,
    or extract data from websites:
    1. Invoke `scrape_web_page` with the target URL.
    2. Read the resulting Markdown representation.
    3. Synthesize the findings accurately with direct citations.
    """,
    tools=[scrape_web_page],
)

5. Security & Isolation Guidelines

  1. Resource Denial of Service (DoS): Launching Chromium processes is memory-intensive (~100–300 MB RAM per instance). In production, configure browser pooling or delegate to hosted browser services (e.g., Browserbase, Steel, or an isolated container).
  2. Server-Side Request Forgery (SSRF): Never allow the agent to scrape internal private IP addresses (127.0.0.1, 169.254.169.254, 10.0.0.0/8). Validate that the target hostname resolves to a public routable IP before launching the browser.
  3. Execution Sandboxing: If running inside Docker, ensure chromium runs under an unprivileged user (RUN useradd -m appuser) rather than root.

Takeaway: Combining asynchronous Playwright extraction with intelligent HTML-to-Markdown distillation provides Google ADK agents with full visibility into modern dynamic web applications while conserving model token budgets.

Sources