unclecode/crawl4ai

β–² 98 stars todayβ˜… 83,563β‘‚ 8,634

πŸš€πŸ€– Crawl4AI: Open-source LLM Friendly Web Crawler & Scraper. Don't be shy, join here: https://discord.gg/jP8KfhDhyN

83,563Star
8,634Fork
414Watch
195Issue
PythonLanguage
Apache-2.0License
Created 2024-05-09 Β· last push 2026-09-14 Β· repository size 151263 KB Β· default branch main

README

πŸš€πŸ€– Crawl4AI: Open-source LLM Friendly Web Crawler & Scraper.

https://github.com/unclecode/crawl4ai/blob/HEAD/unclecode%2Fcrawl4ai | Trendshift

GitHub Stars GitHub Forks

PyPI version Python Version Downloads GitHub Sponsors

---

πŸš€ Crawl4AI Cloud API β€” Closed Beta (Launching Soon)

Reliable, large-scale web extraction, now built to be _drastically more cost-effective_ than any of the existing solutions.

πŸ‘‰ Apply here for early access _We’ll be onboarding in phases and working closely with early users. Limited slots._

---

https://github.com/unclecode/crawl4ai/blob/HEAD/Follow on X https://github.com/unclecode/crawl4ai/blob/HEAD/Follow on LinkedIn https://github.com/unclecode/crawl4ai/blob/HEAD/Join our Discord

Crawl4AI turns the web into clean, LLM ready Markdown for RAG, agents, and data pipelines. Fast, controllable, battle tested by a 50k+ star community.

✨ Check out latest update v0.9.3

✨ New in v0.9.3: Security release. Closes five coordinated-disclosure advisories: arbitrary file write, SSRF, and denial of service in the PDF processing path, plus two XSS issues in the Docker Playground. Also ships 33 bug fixes across the Docker server, crawler, and PDF handling. No new features, no breaking changes. Release notes β†’

✨ Recent v0.9.2: Maintenance patch release. Fixes a MemoryAdaptiveDispatcher task/page leak when a streaming crawl is closed, Docker Playground "Advanced Config" and Monitor WebSocket auth, Playwright headless-shell packaging, and GPU (ENABLE_GPU=true) Docker builds. Release notes β†’

✨ Recent v0.9.0: Major secure-by-default release of the Docker API server. Auth is on by default, the server binds loopback unless given a token, and the request body is now an untrusted trust boundary. Release notes β†’

✨ Recent v0.8.7: Security-hardening release. Fixes critical Docker API vulnerabilities (RCE, SSRF, auth bypass, file write, XSS, hardcoded JWT secret), adds DomainMapper, and ships scraping, deep-crawl, and LLM fixes. Release notes β†’

✨ Previous v0.8.0: Crash Recovery & Prefetch Mode! Deep crawl crash recovery with resume_state and on_state_change callbacks for long-running crawls. New prefetch=True mode for 5-10x faster URL discovery. Release notes β†’

✨ Previous v0.7.8: Stability & Bug Fix Release! 11 bug fixes addressing Docker API issues, LLM extraction improvements, URL handling fixes, and dependency updates. Release notes β†’

πŸ€“ My Personal Story

I grew up on an Amstrad, thanks to my dad, and never stopped building. In grad school I specialized in NLP and built crawlers for research. That’s where I learned how much extraction matters.

In 2023, I needed web-to-Markdown. The β€œopen source” option wanted an account, API token, and $16, and still under-delivered. I went turbo anger mode, built Crawl4AI in days, and it went viral. Now it’s the most-starred crawler on GitHub.

I made it open source for availability, anyone can use it without a gate. Now I’m building the platform for affordability, anyone can run serious crawls without breaking the bank. If that resonates, join in, send feedback, or just crawl something amazing.

Why developers pick Crawl4AI
  • LLM ready output, smart Markdown with headings, tables, code, citation hints
  • Fast in practice, async browser pool, caching, minimal hops
  • Full control, sessions, proxies, cookies, user scripts, hooks
  • Adaptive intelligence, learns site patterns, explores only what matters
  • Deploy anywhere, zero keys, CLI and Docker, cloud friendly

πŸš€ Quick Start

1. Install Crawl4AI:

# Install the package
pip install -U crawl4ai

For pre release versions

pip install crawl4ai --pre

Run post-installation setup

crawl4ai-setup

Verify your installation

crawl4ai-doctor

If you encounter any browser-related issues, you can install them manually:

python -m playwright install --with-deps chromium

2. Run a simple web crawl with Python:

import asyncio
from crawl4ai import *

async def main(): async with AsyncWebCrawler() as crawler: result = await crawler.arun( url="https://www.nbcnews.com/business", ) print(result.markdown)

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

3. Or use the new command-line interface:

# Basic crawl with markdown output
crwl https://www.nbcnews.com/business -o markdown

Deep crawl with BFS strategy, max 10 pages

crwl https://docs.crawl4ai.com --deep-crawl bfs --max-pages 10

Use LLM extraction with a specific question

crwl https://www.example.com/products -q "Extract all product prices"

πŸ’– Support Crawl4AI

πŸŽ‰ Sponsorship Program Now Open! After powering 51K+ developers and 1 year of growth, Crawl4AI is launching dedicated support for startups and enterprises. Be among the first 50 Founding Sponsors for permanent recognition in our Hall of Fame.

Crawl4AI is the #1 trending open-source web crawler on GitHub. Your support keeps it independent, innovative, and free for the community β€” while giving you direct access to premium benefits.

Become a Sponsor Current Sponsors

🀝 Sponsorship Tiers

Custom arrangements available - see SPONSORS.md for details & contact

Why sponsor? No rate-limited APIs. No lock-in. Build and own your data pipeline with direct guidance from the creator of Crawl4AI.

See All Tiers & Benefits β†’

✨ Features

πŸ“ Markdown Generation
  • 🧹 Clean Markdown: Generates clean, structured Markdown with accurate formatting.
  • 🎯 Fit Markdown: Heuristic-based filtering to remove noise and irrelevant parts for AI-friendly processing.
  • πŸ”— Citations and References: Converts page links into a numbered reference list with clean citations.
  • πŸ› οΈ Custom Strategies: Users can create their own Markdown generation strategies tailored to specific needs.
  • πŸ“š BM25 Algorithm: Employs BM25-based filtering for extracting core information and removing irrelevant content.
πŸ“Š Structured Data Extraction
  • πŸ€– LLM-Driven Extraction: Supports all LLMs (open-source and proprietary) for structured data extraction.
  • 🧱 Chunking Strategies: Implements chunking (topic-based, regex, sentence-level) for targeted content processing.
  • 🌌 Cosine Similarity: Find relevant content chunks based on user queries for semantic extraction.
  • πŸ”Ž CSS-Based Extraction: Fast schema-based data extraction using XPath and CSS selectors.
  • πŸ”§ Schema Definition: Define custom schemas for extracting structured JSON from repetitive patterns.
🌐 Browser Integration
  • πŸ–₯️ Managed Browser: Use user-owned browsers with full control, avoiding bot detection.
  • πŸ”„ Remote Browser Control: Connect to Chrome Developer Tools Protocol for remote, large-scale data extraction.
  • πŸ‘€ Browser Profiler: Create and manage persistent profiles with saved authentication states, cookies, and settings.
  • πŸ”’ Session Management: Preserve browser states and reuse them for multi-step crawling.
  • 🧩 Proxy Support: Seamlessly connect to proxies with authentication for secure access.
  • βš™οΈ Full Browser Control: Modify headers, cookies, user agents, and more for tailored crawling setups.
  • 🌍 Multi-Browser Support: Compatible with Chromium, Firefox, and WebKit.
  • πŸ“ Dynamic Viewport Adjustment: Automatically adjusts the browser viewport to match page content, ensuring complete rendering and capturing of all elements.
πŸ”Ž Crawling & Scraping
  • πŸ–ΌοΈ Media Support: Extract images, audio, videos, and responsive image formats like srcset and picture.
  • πŸš€ Dynamic Crawling: Execute JS and wait for async or sync for dynamic content extraction.
  • πŸ“Έ Screenshots: Capture page screenshots during crawling for debugging or analysis.
  • πŸ“‚ Raw Data Crawling: Directly process raw HTML (raw:) or local files (file://).
  • πŸ”— Comprehensive Link Extraction: Extracts internal, external links, and embedded iframe content.
  • πŸ› οΈ Customizable Hooks: Define hooks at every step to customize crawling behavior (supports both string and function-based APIs).
  • πŸ’Ύ Caching: Cache data for improved speed and to avoid redundant fetches.
  • πŸ“„ Metadata Extraction: Retrieve structured metadata from web pages.
  • πŸ“‘ IFrame Content Extraction: Seamless extraction from embedded iframe content.
  • πŸ•΅οΈ Lazy Load Handling: Waits for images to fully load, ensuring no content is missed due to lazy loading.
  • πŸ”„ Full-Page Scanning: Simulates scrolling to load and capture all dynamic content, perfect for infinite scroll pages.
πŸš€ Deployment
  • 🐳 Dockerized Setup: Optimized Docker image with FastAPI server for easy deployment.
  • πŸ”‘ Secure Authentication: Built-in JWT token authentication for API security.
  • πŸ”„ API Gateway: One-click deployment with secure token authentication for API-based workflows.
  • 🌐 Scalable Architecture: Designed for mass-scale production and optimized server performance.
  • ☁️ Cloud Deployment: Ready-to-deploy configurations for major cloud platforms.
🎯 Additional Features
  • πŸ•ΆοΈ Stealth Mode: Avoid bot detection by mimicking real users.
  • 🏷️ Tag-Based Content Extraction: Refine crawling based on custom tags, headers, or metadata.
  • πŸ”— Link Analysis: Extract and analyze all links for detailed data exploration.
  • πŸ›‘οΈ Error Handling: Robust error management for seamless execution.
  • πŸ” CORS & Static Serving: Supports filesystem-based caching and cross-origin requests.
  • πŸ“– Clear Documentation: Simplified and updated guides for onboarding and advanced usage.
  • πŸ™Œ Community Recognition: Acknowledges contributors and pull requests for transparency.

Try it Now!

✨ Play around with this Open In Colab

✨ Visit our Documentation Website

Installation πŸ› οΈ

Crawl4AI offers flexible installation options to suit various use cases. You can install it as a Python package or use Docker.

🐍 Using pip

Choose the installation option that best fits your needs:

Basic Installation

For basic web crawling and scraping tasks:

pip install crawl4ai
crawl4ai-setup # Setup the browser

By default, this will install the asynchronous version of Crawl4AI, using Playwright for web crawling.

πŸ‘‰ Note: When you install Crawl4AI, the crawl4ai-setup should automatically install and set up Playwright. However, if you encounter any Playwright-related errors, you can manually install it using one of these methods:

1. Through the command line:

   playwright install
   

2. If the above doesn't work, try this more specific command:

   python -m playwright install chromium
   

This second method has proven to be more reliable in some cases.

---

Installation with Synchronous Version

The sync version is deprecated and will be removed in future versions. If you need the synchronous version using Selenium:

pip install crawl4ai[sync]

---

Development Installation

For contributors who plan to modify the source code:

git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai
pip install -e .                    # Basic installation in editable mode

Install optional features:

pip install -e ".[torch]"           # With PyTorch features
pip install -e ".[transformer]"     # With Transformer features
pip install -e ".[cosine]"          # With cosine similarity features
pip install -e ".[sync]"            # With synchronous crawling (Selenium)
pip install -e ".[all]"             # Install all optional features

🐳 Docker Deployment
πŸš€ Now Available! Our completely redesigned Docker implementation is here! This new solution makes deployment more efficient and seamless than ever.

New Docker Features

The new Docker implementation includes:

  • Real-time Monitoring Dashboard with live system metrics and browser pool visibility
  • Browser pooling with page pre-warming for faster response times
  • Interactive playground to test and generate request code
  • MCP integration for direct connection to AI tools like Claude Code
  • Comprehensive API endpoints including HTML extraction, screenshots, PDF generation, and JavaScript execution
  • Multi-architecture support with automatic detection (AMD64/ARM64)
  • Optimized resources with improved memory management

Getting Started

# Pull and run the latest release
docker pull unclecode/crawl4ai:latest
docker run -d -p 11235:11235 --name crawl4ai --shm-size=1g unclecode/crawl4ai:latest

Visit the monitoring dashboard at http://localhost:11235/dashboard

Or the playground at http://localhost:11235/playground

Quick Test

Run a quick test (works for both Docker options):

import requests

Submit a crawl job

response = requests.post( "http://localhost:11235/crawl", json={"urls": ["https://example.com"], "priority": 10} ) if response.status_code == 200: print("Crawl job submitted successfully.") if "results" in response.json(): results = response.json()["results"] print("Crawl job completed. Results:") for result in results: print(result) else: task_id = response.json()["task_id"] print(f"Crawl job submitted. Task ID:: {task_id}") result = requests.get(f"http://localhost:11235/task/{task_id}")

For more examples, see our Docker Examples. For advanced configuration, monitoring features, and production deployment, see our Self-Hosting Guide.

---

πŸ”¬ Advanced Usage Examples πŸ”¬

You can check the project structure in the directory docs/examples. Over there, you can find a variety of examples; here, some popular examples are shared.

πŸ“ Heuristic Markdown Generation with Clean and Fit Markdown
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
from crawl4ai.content_filter_strategy import PruningContentFilter, BM25ContentFilter
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator

async def main(): browser_config = BrowserConfig( headless=True, verbose=True, ) run_config = CrawlerRunConfig( cache_mode=CacheMode.ENABLED, markdown_generator=DefaultMarkdownGenerator( content_filter=PruningContentFilter(threshold=0.48, threshold_type="fixed", min_word_threshold=0) ), # markdown_generator=DefaultMarkdownGenerator( # content_filter=BM25ContentFilter(user_query="WHEN_WE_FOCUS_BASED_ON_A_USER_QUERY", bm25_threshold=1.0) # ), ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url="https://docs.micronaut.io/4.9.9/guide/", config=run_config ) print(len(result.markdown.raw_markdown)) print(len(result.markdown.fit_markdown))

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

πŸ–₯️ Executing JavaScript & Extract Structured Data without LLMs
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
from crawl4ai import JsonCssExtractionStrategy
import json

async def main(): schema = { "name": "KidoCode Courses", "baseSelector": "section.charge-methodology .w-tab-content > div", "fields": [ { "name": "section_title", "selector": "h3.heading-50", "type": "text", }, { "name": "section_description", "selector": ".charge-content", "type": "text", }, { "name": "course_name", "selector": ".text-block-93", "type": "text", }, { "name": "course_description", "selector": ".course-content-text", "type": "text", }, { "name": "course_icon", "selector": ".image-92", "type": "attribute", "attribute": "src" } ] }

extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True)

browser_config = BrowserConfig( headless=False, verbose=True ) run_config = CrawlerRunConfig( extraction_strategy=extraction_strategy, js_code=["""(async () => {const tabs = document.querySelectorAll("section.charge-methodology .tabs-menu-3 > div");for(let tab of tabs) {tab.scrollIntoView();tab.click();await new Promise(r => setTimeout(r, 500));}})();"""], cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url="https://www.kidocode.com/degrees/technology", config=run_config )

companies = json.loads(result.extracted_content) print(f"Successfully extracted {len(companies)} companies") print(json.dumps(companies[0], indent=2))

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

πŸ“š Extracting Structured Data with LLMs
import os
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode, LLMConfig
from crawl4ai import LLMExtractionStrategy
from pydantic import BaseModel, Field

class OpenAIModelFee(BaseModel): model_name: str = Field(..., description="Name of the OpenAI model.") input_fee: str = Field(..., description="Fee for input token for the OpenAI model.") output_fee: str = Field(..., description="Fee for output token for the OpenAI model.")

async def main(): browser_config = BrowserConfig(verbose=True) run_config = CrawlerRunConfig( word_count_threshold=1, extraction_strategy=LLMExtractionStrategy( # Here you can use any provider that Litellm library supports, for instance: ollama/qwen2 # provider="ollama/qwen2", api_token="no-token", llm_config = LLMConfig(provider="openai/gpt-4o", api_token=os.getenv('OPENAI_API_KEY')), schema=OpenAIModelFee.schema(), extraction_type="schema", instruction="""From the crawled content, extract all mentioned model names along with their fees for input and output tokens. Do not miss any models in the entire content. One extracted model JSON format should look like this: {"model_name": "GPT-4", "input_fee": "US$10.00 / 1M tokens", "output_fee": "US$30.00 / 1M tokens"}.""" ), cache_mode=CacheMode.BYPASS, ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url='https://openai.com/api/pricing/', config=run_config ) print(result.extracted_content)

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

πŸ€– Using Your own Browser with Custom User Profile
import os, sys
from pathlib import Path
import asyncio, time
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode

async def test_news_crawl(): # Create a persistent user data directory user_data_dir = os.path.join(Path.home(), ".crawl4ai", "browser_profile") os.makedirs(user_data_dir, exist_ok=True)

browser_config = BrowserConfig( verbose=True, headless=True, user_data_dir=user_data_dir, use_persistent_context=True, ) run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler(config=browser_config) as crawler: url = "ADDRESS_OF_A_CHALLENGING_WEBSITE" result = await crawler.arun( url, config=run_config, magic=True, ) print(f"Successfully crawled {url}") print(f"Content length: {len(result.markdown)}")

---

✨ Recent Updates

Version 0.9.3 Release Highlights - Security Release

A security release closing five coordinated-disclosure advisories. Four are in the PDF processing path: an arbitrary file write through PDFContentScrapingStrategy image-write fields, an SSRF where the PDF download followed redirects into internal addresses, a denial of service from unbounded PDF size and page count, and an XSS from unescaped PDF text in cleaned_html. The fifth is a DOM-based XSS in the Docker Playground that could expose the opera

More Today's Trending projects

1

alibaba / open-code-review

Goβ˜… 28,122β‘‚ 2,023β–² 2,751 stars
β†’
2

debpalash / VoiceStudio

Pythonβ˜… 30,697β‘‚ 3,683β–² 2,081 stars
β†’
3

JustVugg / colibri

Cβ˜… 33,539β‘‚ 3,522β–² 2,035 stars
β†’
4

tt-a1i / archify

JavaScriptβ˜… 63,354β‘‚ 4,208β–² 1,407 stars
β†’
5

cloudflare / security-audit-skill

JavaScriptβ˜… 4,982β‘‚ 310β–² 1,210 stars
β†’
6

Panniantong / Agent-Reach

Pythonβ˜… 81,982β‘‚ 7,140β–² 1,094 stars
β†’