Crawl4AI

repository·main·Indexed 13 days ago

https://github.com/unclecode/crawl4ai

An open-source, LLM-friendly web crawler and scraper that converts web content into structured Markdown for RAG, AI agents, and data pipelines. It features a REST API, Model Context Protocol (MCP) support for AI clients like Claude Code, and specialized endpoints for HTML extraction, screenshots, PDF export, and JavaScript execution. Version 0.8.6 supports multi-arch Docker deployments with configurable installation types (default, all, torch, transformer) and GPU support.

Tokens
284.7K
Snippets
670
Records
877
Agent score
91%

What's inside Crawl4AI

  1. Overview of Crawl4AI features

    main

    Crawl4AI provides a comprehensive suite of features for LLM-friendly web scraping:

    Markdown Generation

    • Clean Markdown: Structured formatting.
    • Fit Markdown: Heuristic filtering to remove noise.
    • Citations: Converts links into numbered reference lists.
    • BM25 Algorithm: Filtering for core information extraction.

    Structured Data Extraction

    • LLM-Driven: Supports all major LLMs.
    • Chunking: Topic-based, regex, or sentence-level strategies.
    • Semantic Extraction: Uses Cosine Similarity to find relevant content.
    • CSS/XPath: Fast schema-based extraction.

    Browser & Crawling

    • Managed Browsers: Full control over Chromium, Firefox, and WebKit.
    • Stealth Mode: Mimics real users to avoid detection.
    • Dynamic Content: Executes JS, handles lazy loading, and simulates scrolling for infinite pages.
    • Media & IFrame: Extracts images, audio, video, and content from embedded iframes.
  2. Core Capabilities of Crawl4AI

    main

    Crawl4AI is designed to be an LLM-friendly web crawler and scraper. Its primary functions include:

    • Clean Markdown Generation: Produces well-structured Markdown optimized for RAG (Retrieval-Augmented Generation) pipelines and LLM ingestion.
    • Structured Extraction: Supports parsing data using CSS selectors, XPath, or LLM-based extraction strategies.
    • Advanced Browser Control: Provides fine-grained control via hooks, proxy support, stealth modes, and session re-use.
    • High Performance: Enables parallel crawling and chunk-based extraction for real-time and large-scale use cases.
    • Open Source: Fully open-source with no mandatory API keys or paywalls.
  3. Crawl4AI Brand Guidelines Overview

    main
    The Crawl4AI Brand Book defines a design system intended for building consistent, terminal-inspired user experiences. It provides a cohesive visual language through specific color palettes, typography, component styles (like buttons and badges), and layout patterns to ensure a unified look and feel across all interfaces related to the project.
  4. What is C4A-Script?

    main
    C4A-Script is a human-readable domain-specific language (DSL) designed for web automation and interaction. It allows users to automate repetitive web tasks, test user interfaces, or create interactive demos using simple, English-like commands. It supports both text-based scripting and a visual drag-and-drop programming interface via Google Blockly.
  5. What is storage_state in Crawl4AI?

    main

    In Crawl4AI, storage_state is a mechanism used to preserve and reuse session data, such as cookies and localStorage, across multiple crawler runs. This allows you to start a crawl in an authenticated or pre-configured state (e.g., already logged in) without repeating the login flow every time.

    storage_state can be provided in two formats:

    1. A dictionary: Containing cookies and origins (which holds localStorage data).
    2. A file path: A string pointing to a JSON file that holds the session information.
    {
      "cookies": [
        {
          "name": "session",
          "value": "abcd1234",
          "domain": "example.com",
          "path": "/",
          "expires": 1675363572.037711,
          "httpOnly": false,
          "secure": false,
          "sameSite": "None"
        }
      ],
      "origins": [
        {
          "origin": "https://example.com",
          "localStorage": [
            { "name": "token", "value": "my_auth_token" },
            { "name": "refreshToken", "value": "my_refresh_token" }
          ]
        }
      ]
    }
  6. What is the Builtin Browser in Crawl4AI?

    main

    The builtin browser is a persistent Chrome instance managed by Crawl4AI that runs in the background. Instead of starting and stopping a new browser for every individual crawl, multiple crawling operations can share this single instance.

    Key Benefits:

    • Faster startup times: The browser is already running when your script starts.
    • Shared resources: Multiple scripts can utilize the same instance.
    • Simplified management: You don't need to manually handle CDP (Chrome DevTools Protocol) URLs or browser processes.
    • Persistent state: Cookies and sessions persist between different script runs.
    • Efficiency: Reduces overall system resource usage by avoiding redundant browser processes.
  7. What is Fit Markdown and how does it work?

    main

    Concept

    Fit Markdown is a filtered version of a page's markdown that focuses on the most relevant content by removing low-value sections like sidebars, repetitive text, or shallow blocks.

    While result.markdown.raw_markdown contains the full, unfiltered conversion of the HTML, Fit Markdown uses a content_filter applied during the HTML→Markdown process to produce a concise "core" of text.

    Output Fields

    When using a content filter, the result.markdown object provides three distinct outputs:

    • result.markdown.raw_markdown: The unfiltered markdown.
    • result.markdown.fit_markdown: The filtered/pruned version of the markdown.
    • result.markdown.fit_html: The specific HTML snippet that corresponds to the fit_markdown content.
  8. What is Adaptive Crawling

    main

    Adaptive Crawling is a paradigm shift from traditional brute-force deep crawling to an intelligent, query-driven approach. Instead of crawling an entire site to find information, the system builds knowledge dynamically based on specific queries. It uses information theory and statistical methods (or semantic embeddings) to evaluate links by their probability of contributing meaningful information, allowing the crawler to 'know when to stop' once information saturation is reached.

    Key benefits include:

    • Cost Reduction: Significantly lower LLM token usage by filtering irrelevant content.
    • Efficiency: Faster crawl times by avoiding unnecessary pages.
    • Relevance: Focuses on building a knowledge base that directly answers specific user queries.
  9. Implement crash recovery for long-running crawls

    main

    Crawl4AI supports state persistence to resume crawls if a process is interrupted. This is achieved using two parameters in your deep crawl strategy:

    1. on_state_change: An async callback function that is triggered after every URL is processed. Use this to save the current state to a database or file.
    2. resume_state: A dictionary containing a previously saved state. When passed to the strategy, the crawler will skip already-visited URLs and continue from the pending queue.

    State Structure

    The state dictionary is JSON-serializable and includes:

    • strategy_type: "bfs", "dfs", or "best_first"
    • visited: List of already crawled URLs
    • pending: List of {"url": "...", "parent_url": "..."} objects
    • depths: Mapping of url: depth
    • pages_crawled: Integer counter

    Manual State Export

    If you have on_state_change enabled, you can manually retrieve the current state using strategy.export_state().

    # Callback to save state
    async def save_state_to_redis(state: dict):
        await redis.set("crawl_state", json.dumps(state))
    
    # Strategy with recovery
    strategy = BFSDeepCrawlStrategy(
        max_depth=3,
        on_state_change=save_state_to_redis,
    )
    
    # Resuming later
    saved_state = json.loads(await redis.get("crawl_state"))
    strategy = BFSDeepCrawlStrategy(
        max_depth=3,
        resume_state=saved_state,
        on_state_change=save_state_to_redis,
    )
  10. Implement Deep Crawl Crash Recovery

    main

    To prevent losing progress during long-running deep crawls (BFS, DFS, or Best-First), use the on_state_change callback and the resume_state parameter in your crawling strategy. This allows you to save the crawl state to a persistent store like Redis and resume from where you left off if the process crashes.

    Workflow:

    1. Define a callback function (e.g., save_to_redis) that accepts the current state.
    2. Pass this to the strategy's on_state_change parameter.
    3. To resume, pass the previously saved state to the resume_state parameter.
    from crawl4ai.deep_crawling import BFSDeepCrawlStrategy
    
    strategy = BFSDeepCrawlStrategy(
        max_depth=3,
        resume_state=saved_state,  # Continue from checkpoint
        on_state_change=save_to_redis,  # Called after each URL
    )
  11. Use Hooks in AsyncWebCrawler for advanced automation

    main

    Crawl4AI provides a hook system via crawler.crawler_strategy.set_hook() to intercept and modify different stages of the crawling lifecycle. This is ideal for handling authentication, blocking resources (like images/ads), injecting custom headers, or performing final page manipulations before HTML retrieval.

    Hook NameTimingRecommended Use Case
    on_browser_createdAfter browser instance is created, before pages/contexts exist.Light setup only. Do not open/close pages here.
    on_page_context_createdRight after a new page and context are created.Authentication (login, cookies, localStorage), route filtering (blocking images/ads), or viewport adjustment.
    before_gotoBefore navigating to a URL.Injecting custom HTTP headers.
    after_gotoAfter navigation completes.Verifying page state (e.g., wait_for_selector).
    on_user_agent_updatedWhenever the user agent changes.Logging or reacting to stealth/UA changes.
    on_execution_startedWhen custom JavaScript execution begins.Logging JS execution start.
    before_retrieve_htmlBefore final HTML retrieval.Final page actions like scrolling to the bottom.
    before_return_htmlJust before returning HTML to the CrawlResult.Logging HTML length or minor modifications.

    Key Implementation Details

    • Authentication: The recommended place for login flows is on_page_context_created. This ensures the context is configured before arun() navigates to the target URL.
    • Concurrency: When using arun_many(), hooks are triggered in parallel for each URL. Ensure hook logic is async-safe.
    • Session Management: To reuse a session across multiple arun() calls, pass session_id= in your CrawlerRunConfig.
    import asyncio
    from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
    from playwright.async_api import Page, BrowserContext
    
    async def main():
        browser_config = BrowserConfig(headless=True)
        crawler_run_config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS)
        crawler = AsyncWebCrawler(config=browser_config)
    
        # Define a hook
        async def on_page_context_created(page: Page, context: BrowserContext, **kwargs):
            # Example: Block images
            async def route_filter(route):
                if route.request.resource_type == "image":
                    await route.abort()
                else:
                    await route.continue_()
            await context.route("**", route_filter)
            return page
    
        # Attach the hook
        crawler.crawler_strategy.set_hook("on_page_context_created", on_page_context_created)
    
        await crawler.start()
        result = await crawler.arun("https://example.com", config=crawler_run_config)
        await crawler.close()
    
    if __name__ == "__main__":
        asyncio.run(main())
  12. Configure a RateLimiter for request pacing and backoff

    main

    The RateLimiter component provides smart request pacing and automatic backoff strategies to avoid being blocked by target websites. It handles delays and retries internally without requiring manual implementation in your crawl loop.

    Key configuration capabilities include:

    • Random delay range: Setting a minimum and maximum delay between requests.
    • Maximum backoff delay: Defining the upper limit for exponential backoff.
    • Retries: Specifying the number of attempts before a URL is marked as failed.
    • Status code triggers: Defining which HTTP status codes (e.g., 429 Too Many Requests) should trigger the backoff mechanism.