Crawl4AI Tutorial: Ein Leitfaden für Anfänger

Im AI-Zeitalter: Effizientes Webdaten-Zugreifen essentiell. Crawl4AI: Open-Source-Crawler für LLMs, AI-Agenten & moderne Datenpipelines. Tutorial: Installation bis fortgeschrittene Techniken.

Leo Schulz

Leo Schulz

5 June 2025

Crawl4AI Tutorial: Ein Leitfaden für Anfänger

Im Zeitalter der KI ist der effiziente Zugriff auf und die Verarbeitung von Webdaten entscheidend. Crawl4AI entwickelt sich zu einem leistungsstarken, quelloffenen Webcrawler und -scraper, der sorgfältig für Entwickler entwickelt wurde, die mit Large Language Models (LLMs), KI-Agenten und modernen Datenpipelines arbeiten. Dieses Tutorial bietet einen tiefen Einblick in Crawl4AI und behandelt alles von der Installation bis hin zu fortgeschrittenen Crawling-Techniken.

💡
Want a great API Testing tool that generates beautiful API Documentation?

Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?

Apidog delivers all your demans, and replaces Postman at a much more affordable price!
button

Warum Crawl4AI für Ihre Projekte wählen?

Crawl4AI ist mehr als nur ein Standard-Web-Scraper. Es wurde von Grund auf so konzipiert, dass es LLM-freundlich ist. Das bedeutet, dass es sich konzentriert auf:

Crawl4AI zielt darauf ab, den Datenzugriff zu demokratisieren und Entwicklern die Möglichkeit zu geben, Webdaten schnell und effizient zu sammeln und zu gestalten.


Installieren und Einrichten von Crawl4AI

Crawl4AI zum Laufen zu bringen ist unkompliziert und bietet sowohl pip- als auch Docker-Optionen.

Methode 1: Pip-Installation (empfohlen für die Bibliotheksverwendung)

Paket installieren: Öffnen Sie Ihr Terminal und führen Sie Folgendes aus:

# Install the latest stable version
pip install -U crawl4ai

# Or, install the latest pre-release (for cutting-edge features)
# pip install crawl4ai --pre

Post-Installation-Setup ausführen: Dieser entscheidende Schritt installiert die erforderlichen Playwright-Browser-Binärdateien (standardmäßig Chromium):

crawl4ai-setup

Überprüfen: Überprüfen Sie Ihr Setup mit dem Diagnose-Tool:

crawl4ai-doctor

Fehlerbehebung: Wenn crawl4ai-setup auf Probleme stößt, installieren Sie die Browser-Abhängigkeiten manuell:

python -m playwright install --with-deps chromium

Methode 2: Docker-Bereitstellung (ideal für API-Dienste)

Image abrufen: Holen Sie sich das offizielle Docker-Image (überprüfen Sie GitHub auf das neueste Tag):

# Example tag, replace if necessary
docker pull unclecode/crawl4ai:latest

Container ausführen: Starten Sie den Crawl4AI-Dienst und stellen Sie seine API (Standardport 11235) bereit:

docker run -d -p 11235:11235 --name crawl4ai --shm-size=1g unclecode/crawl4ai:latest

Dadurch wird Crawl4AI mit einem FastAPI-Backend ausgeführt, das bereit ist, Crawl-Anforderungen über HTTP anzunehmen. Sie können über http://localhost:11235/playground auf einen interaktiven API-Spielplatz zugreifen.


So führen Sie Ihren ersten Crawl mit Crawl4AI aus

Crawl4AI macht das grundlegende Crawling mit dem AsyncWebCrawler unglaublich einfach.

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode

async def run_basic_crawl():
    # --- Basic Example ---
    print("--- Running Basic Crawl ---")
    # Use 'async with' for automatic browser startup and shutdown
    async with AsyncWebCrawler() as crawler:
        # The arun() method performs the crawl for a single URL
        # It returns a CrawlResult object
        result = await crawler.arun(url="https://example.com")

        if result and result.success:
            # Access the generated Markdown (usually 'fit_markdown')
            print("Crawl Successful!")
            # result.markdown provides both raw and filtered markdown
            print(f"Fit Markdown (first 300 chars): {result.markdown.fit_markdown[:300]}...")
        else:
            print(f"Crawl Failed: {result.error_message}")

    # --- Example with Basic Configuration ---
    print("\n--- Running Crawl with Basic Configuration ---")
    # Configure browser behavior (e.g., run headful for debugging)
    browser_conf = BrowserConfig(headless=True) # Set to False to see the browser window

    # Configure run-specific settings (e.g., bypass cache)
    # CacheMode.ENABLED (default), CacheMode.DISABLED, CacheMode.BYPASS
    run_conf = CrawlerRunConfig(cache_mode=CacheMode.BYPASS)

    async with AsyncWebCrawler(config=browser_conf) as crawler:
        result = await crawler.arun(
            url="https://crawl4ai.com/", # Crawl the official site
            config=run_conf # Apply the run configuration
        )
        if result and result.success:
            print("Crawl Successful!")
            print(f"Fit Markdown Word Count: {result.markdown.word_count}")
            print(f"URL Crawled: {result.url}")
        else:
            print(f"Crawl Failed: {result.error_message}")

if __name__ == "__main__":
    asyncio.run(run_basic_crawl())

Wichtige Crawl4AI-Konzepte:


Wie funktioniert das Crawl4AI CrawlResult-Objekt?

Jeder erfolgreiche arun- oder arun_many-Aufruf gibt ein oder mehrere CrawlResult-Objekte zurück, die alle während des Crawls gesammelten Informationen kapseln.

Das CrawlResult-Objekt enthält verschiedene Attribute, darunter:

Die Inspektion dieses Objekts ist der Schlüssel zum Zugriff auf die spezifischen Daten, die Sie von einem Crawl4AI-Crawl benötigen.


So generieren Sie KI-fähiges Markdown mit Crawl4AI

Eine Kernstärke von Crawl4AI ist die Fähigkeit, sauberes Markdown zu generieren, das für LLMs geeignet ist.

Das Attribut result.markdown enthält:

Sie können den Filterprozess in Crawl4AI anpassen:

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
# Import specific strategies for customization
from crawl4ai.content_filter_strategy import PruningContentFilter
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator

async def run_custom_markdown_crawl():
    print("\n--- Running Crawl with Custom Markdown Filtering ---")

    # Configure a Markdown generator with a specific content filter
    # PruningContentFilter removes elements based on word count thresholds
    markdown_generator_with_filter = DefaultMarkdownGenerator(
        content_filter=PruningContentFilter(
            threshold=0.48, # Adjust threshold (0 to 1) for strictness
            threshold_type="fixed" # 'fixed' or 'relative'
            )
    )

    # Apply this generator in the run configuration
    run_conf = CrawlerRunConfig(
        cache_mode=CacheMode.BYPASS,
        markdown_generator=markdown_generator_with_filter
    )

    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(
            url="https://www.nbcnews.com/business", # A news site often has clutter
            config=run_conf
        )
        if result and result.success:
            print("Crawl Successful!")
            print(f"Raw Markdown Length: {len(result.markdown.raw_markdown)}")
            print(f"Fit Markdown Length: {len(result.markdown.fit_markdown)}") # Usually shorter
            # Compare raw_markdown and fit_markdown to see the filter's effect
        else:
            print(f"Crawl Failed: {result.error_message}")

if __name__ == "__main__":
    asyncio.run(run_custom_markdown_crawl())

Durch die Anpassung des content_filter innerhalb des markdown_generator steuern Sie, wie aggressiv Crawl4AI den Inhalt bereinigt, bevor fit_markdown erstellt wird.


So verwenden Sie Crawl4AI Deep Crawling

Crawl4AI ist nicht auf einzelne Seiten beschränkt. Es kann Deep Crawls durchführen und durch eine Website navigieren, indem es Links folgt.

Verwenden Sie die Methode adeep_crawl (oder das crwl-Flag --deep-crawl der CLI):

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode

async def run_deep_crawl():
    print("\n--- Running Deep Crawl ---")
    # Configuration can be applied globally or per-run as usual
    run_conf = CrawlerRunConfig(cache_mode=CacheMode.ENABLED)

    async with AsyncWebCrawler() as crawler:
        # adeep_crawl returns an async generator, yielding results as pages finish
        crawl_generator = await crawler.adeep_crawl(
            start_url="https://docs.crawl4ai.com/", # Starting point
            strategy="bfs", # 'bfs' (Breadth-First), 'dfs' (Depth-First), 'bestfirst'
            max_depth=2,    # Limit how many links deep to follow
            max_pages=10,   # Limit the total number of pages to crawl
            config=run_conf
        )

        # Process results as they come in
        pages_crawled = 0
        async for result in crawl_generator:
            if result.success:
                print(f"[OK] Crawled: {result.url} (Depth: {result.depth}, Fit Markdown Length: {len(result.markdown.fit_markdown)})")
                pages_crawled += 1
            else:
                print(f"[FAIL] URL: {result.url}, Error: {result.error_message}")

        print(f"\nDeep crawl finished. Total pages successfully crawled: {pages_crawled}")

if __name__ == "__main__":
    asyncio.run(run_deep_crawl())

Crawl4AI Deep Crawl-Parameter:


So handhaben Sie dynamische Inhalte und Interaktionen mit Crawl4AI

Moderne Websites verlassen sich stark auf JavaScript, um Inhalte zu laden. Crawl4AI verarbeitet dies über die Playwright-Funktionen.

Sie können beliebigen JavaScript-Code ausführen oder auf bestimmte Bedingungen warten, indem Sie CrawlerRunConfig verwenden:

import asyncio
import json
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy # For example

async def crawl_dynamic_page():
    print("\n--- Crawling Dynamic Page with JS Interaction ---")

    # Example schema for CSS extraction (adapt to the target site)
    schema = { "items": { "selector": "div.product-item", "type": "list", "fields": { "title": "h2", "price": ".price" } } }
    css_extractor = JsonCssExtractionStrategy(schema)

    # JavaScript to execute on the page (e.g., click a 'Load More' button)
    # Note: Selector needs to match the target website
    js_to_run = """
    (async () => {
        const loadMoreButton = document.querySelector('button#load-more');
        if (loadMoreButton) {
            console.log('Clicking load more button...');
            loadMoreButton.click();
            // Wait a bit for content to potentially load after click
            await new Promise(resolve => setTimeout(resolve, 2000));
            console.log('Waited after click.');
        } else {
            console.log('Load more button not found.');
        }
    })();
    """

    run_conf = CrawlerRunConfig(
        cache_mode=CacheMode.BYPASS,
        js_code=[js_to_run], # List of JS snippets to execute
        wait_for_timeout=3000, # Wait 3 seconds after initial load AND after JS execution
        # wait_for_selector="div.newly-loaded-content", # Or wait for a specific element
        extraction_strategy=css_extractor, # Extract data after JS runs
        output_formats=['markdown', 'extracted_content']
    )

    # Ensure JS is enabled in BrowserConfig (it is by default)
    browser_conf = BrowserConfig(headless=True, java_script_enabled=True)

    async with AsyncWebCrawler(config=browser_conf) as crawler:
        result = await crawler.arun(
            url="URL_OF_DYNAMIC_PAGE_HERE", # Replace with actual URL
            config=run_conf
        )

        if result and result.success:
            print("Dynamic page crawl successful!")
            print(f"Fit Markdown Length: {len(result.markdown.fit_markdown)}")
            if result.extracted_content:
                try:
                    extracted_data = json.loads(result.extracted_content)
                    print(f"Extracted Content Preview: {json.dumps(extracted_data, indent=2)[:500]}...")
                except json.JSONDecodeError:
                    print(f"Extracted Content (non-JSON): {result.extracted_content[:500]}...")
        else:
            print(f"Crawl Failed: {result.error_message}")


if __name__ == "__main__":
    # Replace with an actual URL that loads content dynamically for testing
    # asyncio.run(crawl_dynamic_page())
    print("Please replace 'URL_OF_DYNAMIC_PAGE_HERE' and uncomment the line above to run the dynamic example.")

Wichtige Crawl4AI-Interaktionsparameter in CrawlerRunConfig:


Crawl4AI Fazit

Crawl4AI bietet eine umfassende, Python-basierte und KI-zentrierte Lösung für Web-Crawling und -Scraping. Sein Fokus auf die Generierung von sauberem Markdown, die flexible Extraktion strukturierter Daten (sowohl CSS- als auch LLM-basiert), die robuste Handhabung dynamischer Inhalte und der effiziente asynchrone Betrieb machen es zu einer ausgezeichneten Wahl für Projekte, die RAG, LLM-Feintuning oder jede Aufgabe erfordern, die strukturierte Informationen aus dem Web benötigt. Durch die Nutzung seiner klaren API, Konfigurationsoptionen (BrowserConfig, CrawlerRunConfig) und des detaillierten CrawlResult-Objekts können Entwickler anspruchsvolle und effiziente Datenbeschaffungs-Workflows erstellen.

💡
Want a great API Testing tool that generates beautiful API Documentation?

Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?

Apidog delivers all your demans, and replaces Postman at a much more affordable price!
button

Explore more

Fathom-R1-14B: Fortschrittliches KI-Argumentationsmodell aus Indien

Fathom-R1-14B: Fortschrittliches KI-Argumentationsmodell aus Indien

Künstliche Intelligenz wächst rasant. FractalAIResearch/Fathom-R1-14B (14,8 Mrd. Parameter) glänzt in Mathe & Logik.

5 June 2025

Cursor 1.0 mit BugBot: KI-gestütztes Automatisierungstest-Tool ist da:

Cursor 1.0 mit BugBot: KI-gestütztes Automatisierungstest-Tool ist da:

Die Softwareentwicklung erlebt Innovationen durch KI. Cursor, ein KI-Editor, erreicht mit Version 1.0 einen Meilenstein.

5 June 2025

30+ öffentliche Web 3.0 APIs, die Sie jetzt nutzen können

30+ öffentliche Web 3.0 APIs, die Sie jetzt nutzen können

Der Aufstieg von Web 3.0: Dezentral, nutzerorientiert, transparent. APIs ermöglichen innovative dApps und Blockchain-Integration.

4 June 2025

Praktizieren Sie API Design-First in Apidog

Entdecken Sie eine einfachere Möglichkeit, APIs zu erstellen und zu nutzen