Back to blog

Crawl4AI Tutorial: Build Powerful AI Web Scrapers

Share article:

Crawl4AI is an open-source Python web-crawling library that uses browser automation to turn web pages into clean, structured data for LLMs. Developers use it to collect AI-ready data for AI agents, RAG systems, and scraping pipelines. This tutorial covers setup, extraction, deep crawling, proxies, and when to use a managed crawling API instead.

AI icon glowing, flanked by code panels labeled AI Parser and HTML/JSON snippets on a dark dotted gradient background

TL;DR

  • Crawl4AI uses Playwright to render web pages and return LLM-ready Markdown or structured JSON.
  • Choose CSS or XPath for stable page structures, and use LLM extraction when the fields require more interpretation.
  • Set depth, page, and URL limits for deep crawls. Also save progress so a failed run can resume.
  • Choose self-hosted Crawl4AI or a managed crawling API based on how much infrastructure, proxy management, and maintenance you want to handle.

What is Crawl4AI, and when should you use it?

Crawl4AI is an open-source Python library that turns website content into clean Markdown or structured data for LLMs, AI agents, and RAG pipelines. It combines browser rendering, asynchronous crawling, content filtering, and data extraction, making it easier to build AI-powered scrapers without managing each part separately.

As of November 2026, its GitHub repository has around 86.6K stars, while pepy.tech reports more than 21.75M cumulative PyPI downloads, including automated downloads. 

Many websites rely on JavaScript to display content such as product prices, job listings, and search results. A basic HTTP scraper might miss this information because it isn't always present in the initial HTML.

Crawl4AI gets around this by using a Playwright-powered browser to render pages before extracting their content. Building a similar workflow yourself means handling browser automation, HTML cleanup, and data extraction with separate tools.

Crawl4AI also helps clean up the information it collects. Instead of returning a page filled with navigation menus, cookie banners, and sidebars, its content filters can remove much of that clutter and produce more useful Markdown.

Code editor showing HTML markup on left and tutorial titled 'What is a Neural Network?' on right in a dark split-view window

You can then feed that content into an AI agent or RAG pipeline, with any necessary chunking and indexing. If you need specific information, such as product names, prices, or job titles, Crawl4AI can also extract structured JSON.

Crawl4AI's main capabilities

Here are some of the features you'll find most useful:

  • CSS, XPath, and LLM extraction. Choose deterministic selectors for stable layouts and a model when a field needs interpretation.
  • Filtered Markdown. Use pruning or BM25 relevance filters to keep useful page sections and reduce noise before ingestion.
  • Asynchronous execution. Reuse a browser session and process multiple pages without starting a new browser for each URL.
  • Deep crawling. Use breadth-first, depth-first, or relevance-based traversal, with URL filters and limits on depth and page count.
  • Browser configuration. Control sessions, JavaScript, proxy settings, and other browser behavior from Python.

How does Crawl4AI compare with other scraping tools?

If you've worked with web scraping before, you've probably come across tools like Scrapy, Selenium, or Beautiful Soup.

Scrapy excels at large-scale request scheduling and structured crawling. However, for JavaScript-heavy pages, you may need to integrate a browser-rendering tool. Selenium automates a real browser and works well for interactive workflows, but cleaning the resulting content and converting it to Markdown or structured data requires extra work.

Beautiful Soup parses HTML you have already fetched, so fetching, rendering, and crawling remain your responsibility. Hosted services such as Firecrawl provide managed extraction and reduce infrastructure work, although you'll need to consider its API pricing and available configuration options. 

Crawl4AI makes sense when you want these crawling and extraction decisions inside an open-source Python workflow.

Installation and setup

Crawl4AI's installation is a two-step process: the Python package first, then the browser binaries. Both need to be verified before you write a single line of crawl code.

Prerequisites

Before you begin, confirm your environment meets the following requirements:

Project setup

Start by creating a virtual environment – an isolated Python workspace that keeps Crawl4AI's dependencies separate from your other projects.

On macOS and Linux:

python -m venv crawl4ai-env
source crawl4ai-env/bin/activate

On Windows:

python -m venv crawl4ai-env
crawl4ai-env\Scripts\activate

Install the package

Run the install:

pip install -U crawl4ai

This installs the core Crawl4AI library. The -U flag tells pip to upgrade an existing installation to the latest available compatible version. You'll still need to install the browser dependencies, which we'll handle next.

crawl4ai-setup

The latter command installs Playwright, alongside other OS-level dependencies your system may need. This is where browser binaries and system dependencies are provisioned, and it's the most common failure point in first-time setups.

Verify the installation

Run a quick check to confirm everything is correctly configured:

crawl4ai-doctor

This checks 3 things: Python version compatibility, whether Playwright is installed correctly, and whether any environment variables or library conflicts could cause runtime problems. If it flags anything, fix it and re-run the command.

Here are some solutions to the errors flagged by crawl4ai-doctor:

  • Playwright not found → run playwright install chromium manually, then re-run crawl4ai-setup
  • Missing system libraries on Linux → install libnss3 libatk-bridge2.0-0 libxss1, then retry
  • Cache directory permission error → check write access to ~/.crawl4ai

Running Crawl4AI in Docker

Crawl4AI also provides an official Docker image for running the crawler as a self-hosted API server. This is useful when you want multiple applications to share a crawling service without running the Python library separately in each project.

The Docker server now includes authentication by default. For the latest image tags, configuration options, and deployment instructions, check the official Crawl4AI self-hosting documentation.

Optional: Full feature install

The base install covers everything this guide requires, including the LLMExtractionStrategy. If you need ML-heavy extras like Torch and Transformers, you can add them explicitly, or use the command below to add all features:

pip install crawl4ai[all]
crawl4ai-setup

With crawl4ai-doctor returning clean, the next step is to put the library to work and see how it handles a real page.

Building and running your first Crawl4AI crawler

Crawl4AI splits configuration across 3 objects that control different things. Mixing them up is the most common source of bugs:

  • AsyncWebCrawler manages the browser session: it opens Chromium, keeps it alive across requests, and closes cleanly when done.
  • BrowserConfig controls how that browser behaves. Headless mode, which user agent to present, proxy configuration, etc. You configure it once when you initialize the crawler.
  • CrawlerRunConfig controls a single crawl run: caching, content filters, and extraction strategy.

Put simply, BrowserConfig defines how the browser runs; CrawlerRunConfig defines what each crawl does.

Your first crawl

Create crawler.py. This file will hold all the crawl logic in this tutorial.

The code below fetches TechCrunch and returns it as Markdown. Since most of the page renders client-side, you get to see Crawl4AI's rendering engine in action:

import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig




async def main():
  
   browser_config = BrowserConfig(headless=True)
   crawler_config = CrawlerRunConfig()




   async with AsyncWebCrawler(config=browser_config) as crawler:
       result = await crawler.arun(
           url="https://techcrunch.com",
           config=crawler_config
       )




       print(result.markdown.raw_markdown)




# Run the async main function
asyncio.run(main())

Using asyncio allows Python to run the event loop that executes AsyncWebCrawler's non-blocking operations.

Here's a sample output of the script:

[Skip to content](https://techcrunch.com/#wp--skip-link--target)
[![](https://techcrunch.com/wp-content/uploads/2024/09/tc-lockup.svg) TechCrunch Desktop Logo](https://techcrunch.com)




 * [Latest](https://techcrunch.com/latest/)
 * [Startups](https://techcrunch.com/category/startups/)
 * [Venture](https://techcrunch.com/category/venture/)
 * [AI](https://techcrunch.com/category/artificial-intelligence/)
 * [Events](https://techcrunch.com/events/)
 * [Newsletters](https://techcrunch.com/newsletters/)




Search · Submit · Site Search Toggle · Mega Menu Toggle




# ... (more lines)

Here, the raw_markdown function gives you the full, unfiltered extraction, including everything Crawl4AI picked up from the page, noise included.

Alternatively, we can use fit_markdown – it offers filtered and cleaned output:

import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, DefaultMarkdownGenerator
from crawl4ai.content_filter_strategy import PruningContentFilter




# Configure the crawler to use a content filter
config = CrawlerRunConfig(
   markdown_generator=DefaultMarkdownGenerator(
       content_filter=PruningContentFilter(threshold=0.5) # 0-1 scale. higher = more aggressive filtering
   )
)




async def main():




  # crawl the target URL with the config above
   async with AsyncWebCrawler() as crawler:
       result = await crawler.arun(
           url="https://techcrunch.com",
           config=config
       )
       print(result.markdown.fit_markdown)  # filtered output, not raw




# Run the async main function
asyncio.run(main())

PruningContentFilter scores each content block by density and relevance, then drops anything below the threshold. Putting it at 0.5 is typically a reasonable default, but you might be losing content you need.

To go further, you can pass a BM25ContentFilter, which filters content by keyword relevance. You pass it a query, and it keeps only the blocks that score above the threshold for that query.

# other imports...
from crawl4ai.content_filter_strategy import BM25ContentFilter




# Configure the crawler to use a BM25 content filter for keyword relevance
config = CrawlerRunConfig(
   markdown_generator=DefaultMarkdownGenerator(
       # BM25ContentFilter keeps only content relevant to the user query
       content_filter=BM25ContentFilter(
           user_query="software engineering jobs",
           bm25_threshold=1.2
       )
   )
)




# rest of the code...

Sample output:

### Startup hiring trends in 2026




Several startups are expanding engineering teams, focusing on backend systems and AI infrastructure.




Companies mentioned:
- Fintech and AI startups hiring engineers




Requirements:
- Python, TypeScript, cloud infrastructure experience

The caveat, however, is that BM25 is still unstructured – you get relevant text blocks, but they're still flat Markdown. You can't reliably extract "this salary belongs to this job title" or "this tech stack belongs to this listing" because BM25 has no concept of relationships between fields.

Extracting structured data with CSS selectors and XPath

CSS selectors have been the backbone of structured extraction since Scrapy's 2008 debut. Crawl4AI's JsonCssExtractionStrategy extends that pattern, but instead of querying one element at a time, you define a schema upfront and get back a list of typed objects.

RemoteOK's job listings follow a consistent DOM structure. Inspect any listing in DevTools and the selectors surface immediately – here's what that looks like in practice:

Browser showing 'WordPress Developer' listing, cursor on 'Apply', HTML inspector open, blurred colorful desktop background

Those selectors map directly to a JsonCssExtractionStrategy schema:

import asyncio
import json
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
 
schema = {
    "name": "Remote Jobs",
    "baseSelector": "tr.job",
    "fields": [
        {"name": "title",    "selector": "td.company_and_position h2",            "type": "text"},
        {"name": "company",  "selector": "td.company_and_position h3",            "type": "text"},
        {"name": "location", "selector": "td.company_and_position div.location",  "type": "text"},
        {"name": "tags",     "selector": "td.tags div.tag h3",                    "type": "list", "fields": [{"name": "tag", "type": "text"}]},
        {"name": "url",      "selector": "td.company_and_position a.preventLink", "type": "attribute", "attribute": "href"},
    ]
}
 
config = CrawlerRunConfig(
    extraction_strategy=JsonCssExtractionStrategy(schema),
    wait_for="css:tr.job",       # hold until job rows are present in the DOM
    page_timeout=30000,           # wait 30 seconds for the page to load
    delay_before_return_html=3.0 # extra buffer for JS to finish rendering
)
 
async def main():
    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(url="https://remoteok.com", config=config)
        jobs = json.loads(result.extracted_content)
        print(json.dumps(jobs[:3], indent=2)) # print the first 3 jobs - indent for readability
 
asyncio.run(main())

Here's what the output looks like then:

[
  {
    "title": "Senior Frontend Engineer",
    "company": "Level",
    "location": "🌏 Worldwide",
    "tags": [{"tag": "Engineer"}, {"tag": "JavaScript"}, {"tag": "React"}],
    "url": "/remote-jobs/remote-senior-frontend-engineer-level-1130614"
  },
  {
    "title": "Crypto Trader",
    "company": "ELEMENTAL TERRA",
    "location": "🌏 Worldwide",
    "tags": [{"tag": "Crypto"}, {"tag": "Web3"}, {"tag": "Finance"}],
    "url": "/remote-jobs/remote-crypto-trader-elemental-terra-1130867"
  }
]

A few important details about Crawl4AI's behavior here:

  • wait_foralone is not enough on JS-rendered pages. It holds the crawler until the target elements appear in the DOM, but the page may still be mid-render at that point. The delay_before_return_html function adds a hard buffer after that condition is met.
  • The list type returns dicts, not strings. Tags come back as [{"tag": "Engineer"}] rather than a flat array.
  • Crawl4AI has no multiple flag. Unlike Beautiful Soup or Scrapy, passing multiple: True does nothing – the schema processes silently and returns only the first match, with no error.

Selectors fail in 2 predictable ways. Timing is the first, which the delay parameters above address as shown. The second failure mode is structural, and there are no parameters for it.

CSS selectors depend on class names and DOM structure. Neither is under your control. If just one class gets renamed, your job listing extraction will return empty objects. This is the most common failure mode in production scrapers, and to make things worse, it fails silently without errors.

If the page structure changes frequently, reach for JsonXPathExtractionStrategy instead. It doesn't eliminate the problem, but since XPath targets elements by text content and position rather than class names, a markup shift is less likely to break your schema. For a more in-depth comparison, check out our XPath vs. CSS selectors guide.

For pages with "Load More" buttons or infinite scroll, use the js_code parameter in CrawlerRunConfig. It accepts a JavaScript string that Crawl4AI executes in the browser before extraction. This lets you trigger whatever is needed to expose content in the DOM – clicking a button, scrolling the page, or dismissing a modal:

config = CrawlerRunConfig(
    extraction_strategy=JsonCssExtractionStrategy(schema),
    wait_for="css:tr.job", # wait until job rows are in the DOM
    js_code="document.querySelector('button.load-more').click();", # trigger load more before extracting
    cache_mode=CacheMode.ENABLED # skip re-crawling unchanged pages
)

It's worth highlighting the use of CacheMode.ENABLED here. Enabling cache mode tells Crawl4AI to save pages it has already crawled, so if your crawler crashes mid-run, you can resume from where you left off. And when the scraping is done, you can save the final output to JSON, CSV, or a database.

A nice perk of enabling caching is that cached pages return almost instantly (fetch times of 0.01s). As such, repeat runs are dramatically faster. Just note that you're getting saved data, not a live crawl. You can always switch back to CacheMode.BYPASS when you need fresh results.

When one page isn't enough: Deep crawling strategies

A single-page crawler works well until the information you need is buried several links deep. Think of a job board with category pages, paginated listings, and individual job descriptions. Crawling just the homepage won't get you very far.

This is where deep crawling becomes useful. Instead of scraping one URL at a time, Crawl4AI can discover and follow links across a website.

It supports three main crawling strategies:

  • Breadth-first search (BFS) explores pages level by level, starting with links closest to the homepage.
  • Depth-first search (DFS) follows one path as far as the configured depth allows before returning to explore other links.
  • BestFirst crawling prioritizes discovered URLs by relevance score, helping you reach potentially useful pages sooner.

Here's how to configure each strategy:

from crawl4ai.deep_crawling import (
    BFSDeepCrawlStrategy,
    DFSDeepCrawlStrategy,
    BestFirstCrawlingStrategy
)
from crawl4ai.deep_crawling.scorers import KeywordRelevanceScorer


# BFS: explore links level by level
bfs = BFSDeepCrawlStrategy(
    max_depth=2,
    max_pages=50
)


# DFS: follow one path before exploring another
dfs = DFSDeepCrawlStrategy(
    max_depth=2,
    max_pages=50
)


# BestFirst: prioritize URLs based on keyword relevance
scorer = KeywordRelevanceScorer(
    keywords=["python", "backend", "engineer"],
    weight=0.7
)


best_first = BestFirstCrawlingStrategy(
    max_depth=2,
    max_pages=50,
    url_scorer=scorer
)

BFS is a good starting point when you want broad coverage of a website. But if you already know what you're looking for, BestFirst offers a more targeted approach.

Let's say you're crawling RemoteOK for Python and backend engineering jobs. Rather than treating every discovered link equally, BestFirst uses a keyword scorer to decide which URLs to visit first.

For example, a URL containing remote-python-jobs will receive a higher score than one containing remote-accounting-jobs when the scorer is looking for Python-related terms.

One important distinction: the keyword scorer evaluates the URL itself, not the content of the page. It helps prioritize links before fetching them, but it doesn't guarantee that the highest-scoring page contains the best result.

Here's how to put that into practice:

import asyncio
import json
from pathlib import Path


from crawl4ai import (
    AsyncWebCrawler,
    BrowserConfig,
    CrawlerRunConfig,
    CacheMode
)
from crawl4ai.deep_crawling import BestFirstCrawlingStrategy
from crawl4ai.deep_crawling.scorers import KeywordRelevanceScorer
from crawl4ai.deep_crawling.filters import FilterChain, URLPatternFilter


STATE_FILE = Path("remoteok-crawl-state.json")




async def save_state(state: dict):
    # Save progress so an interrupted crawl can resume
    temp_file = STATE_FILE.with_suffix(".tmp")
    temp_file.write_text(json.dumps(state), encoding="utf-8")
    temp_file.replace(STATE_FILE)




async def deep_crawl_remoteok():
    # Load a previous checkpoint if one exists
    resume_state = None


    if STATE_FILE.exists():
        resume_state = json.loads(
            STATE_FILE.read_text(encoding="utf-8")
        )


    scorer = KeywordRelevanceScorer(
        keywords=["python", "backend", "engineer"],
        weight=0.7
    )


    strategy = BestFirstCrawlingStrategy(
        max_depth=2,
        max_pages=50,
        include_external=False,
        url_scorer=scorer,
        filter_chain=FilterChain([
            URLPatternFilter(
                patterns=[
                    "*remote-*-jobs*",
                    "*remote-jobs/*"
                ]
            )
        ]),
        on_state_change=save_state,
        resume_state=resume_state
    )


    config = CrawlerRunConfig(
        deep_crawl_strategy=strategy,
        cache_mode=CacheMode.BYPASS,
        stream=True
    )


    async with AsyncWebCrawler(
        config=BrowserConfig(headless=True, chrome_channel="chrome")
    ) as crawler:


        async for result in await crawler.arun(
            url="https://remoteok.com",
            config=config
        ):
            if result.success:
                metadata = result.metadata or {}


                depth = metadata.get("depth", 0)
                score = metadata.get("score", 0.0)


                print(
                    f"[depth {depth} | score {score:.2f}] "
                    f"{result.url}"
                )
            else:
                print(
                    f"[failed] {result.url}: "
                    f"{result.error_message}"
                )


    # Remove the checkpoint after a completed crawl
    STATE_FILE.unlink(missing_ok=True)




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

Here, KeywordRelevanceScorer ranks discovered URLs based on the keywords we've provided, while URLPatternFilter controls which links the crawler follows.

The crawl is limited to two levels beyond the starting page and a maximum of 50 pages. You can adjust these limits depending on the size of the website and how much data you need.

For longer crawls, it's also useful to save your progress. Crawl4AI supports this through two options introduced in v0.8.0:

  • on_state_change lets you save the crawler's progress as it processes URLs
  • resume_state lets you restore that progress when restarting an interrupted crawl

In this example, the callback saves the crawl state to a local JSON file. If the process stops unexpectedly, the next run checks for that file and attempts to pick up where it left off.

We've also enabled streaming, so the crawler prints results as it processes pages instead of waiting for the entire crawl to finish.

Each successful result shows the page's URL, crawl depth, and relevance score. Here's the actual output from our RemoteOK crawl:

[depth 0 | score 0.00] https://remoteok.com
[depth 1 | score 0.23] https://remoteok.com/remote-engineer-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-customer-support-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-education-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-exec-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-finance-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-marketing-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-medical-jobs
[depth 1 | score 0.00] https://remoteok.com/remote-ops-jobs

Notice that remote-engineer-jobs appears first among the discovered pages, with a relevance score of 0.23. This is because its URL matches one of our keywords, engineer. Other categories, such as remote-finance-jobs and remote-marketing-jobs, score 0.00 because their URLs don't contain any of the specified keywords.

The crawler still visits those pages because we haven't set a minimum relevance threshold. BestFirst simply prioritizes the higher-scoring URLs.

You'll also notice that the crawl reaches depth 1, even though we configured a maximum depth of 2. That's expected. The depth setting defines how far the crawler can go, not how far it must go.

This is what makes BestFirst useful when exploring larger websites. You can let the crawler discover links while using relevance scores to decide which pages deserve attention first.

When you don't know how much to crawl

Both BFS and DFS require you to set stopping conditions like max depth and max pages upfront. That only works when you know the site structure. Otherwise, you either set the cap too low and miss data, or too high and crawl into noise.

AdaptiveCrawler flips this. Instead of a traversal pattern, you give it a natural language query, and it determines its own stopping point based on what it finds. But no, there's no LLM involved:

import json
from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig




async def adaptive_crawl_remoteok():
   config = AdaptiveConfig(
       confidence_threshold=0.8,  # Stop at 80% confidence level
       max_pages=30,             
       top_k_links=5,             # Follow the 5 most relevant links per page
       min_gain_threshold=0.05    # Stop if new pages aren't adding much
   )




   async with AsyncWebCrawler() as crawler:
       adaptive = AdaptiveCrawler(crawler, config)




       result = await adaptive.digest(
           start_url="https://remoteok.com",
           query="python backend engineer remote jobs"
       )




       # Crawl statistics: confidence score, pages crawled, coverage
       adaptive.print_stats()




       # Top 5 most relevant pages with relevance scores
       print(json.dumps(adaptive.get_relevant_content(top_k=5), indent=2))

AdaptiveCrawler's default strategy is purely statistical. Behind the scenes, it algorithmically tracks 3 signals per crawl: coverage, consistency, and saturation. No API calls, no extra cost.

However, if you need it to understand query intent semantically, AdaptiveCrawler has an embedding strategy that accepts an LLMConfig.

As a rule of thumb, use BFS when you need comprehensive coverage of a site with known structure, and use AdaptiveCrawler when you need the tool itself to determine the stopping point.

Why your IP gets flagged (and how to fix it)

Our RemoteOK crawler worked in the previous section, but a successful run doesn't mean you can keep sending requests indefinitely. As your request volume increases, websites may limit your access, especially when they detect automated traffic.

And blocking isn't always obvious. Some sites return a 403 error, while others slow down responses, return empty pages, or present a CAPTCHA.

Why your crawler needs a proxy

Proxies can help with three common scraping challenges: IP-based restrictions, geo-restricted content, and distributing requests across multiple IP addresses.

Free proxies might work for basic tests on websites with minimal protection. However, their availability, speed, and IP reputation can be inconsistent. Even sites without obvious anti-bot measures may still limit repeated requests.

For websites with stricter IP-based checks, residential proxies are often a better option. They route requests through IP addresses associated with real household devices and support rotating and sticky sessions.

Here's how to get started:

  1. Create your account. Sign up through the Decodo dashboard.
  2. Select a proxy plan. Choose a subscription that fits your needs, or start with the 3-day free trial.
  3. Configure your proxy settings. Choose rotating sessions for independent requests or sticky sessions when you need to maintain the same IP.
  4. Select your locations. Target specific regions based on your data requirements, or use random locations if you don't need geographical targeting.
  5. Copy your credentials. You'll need your proxy username, password, and server endpoint to connect to Crawl4AI.

Get residential proxies for scraping

Unlock superior scraping performance with a free 3-day trial of Decodo's residential proxy network.

Configuring a proxy in Crawl4AI

Proxy configuration goes on BrowserConfig via proxy_config. It applies to the entire browser session:

from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig


browser_config = BrowserConfig(
    headless=True,
    proxy_config={
        "server": "http://gate.decodo.com:7000",
        "username": "your_username",
        "password": "your_password"
    }
)


async def main():
    async with AsyncWebCrawler(config=browser_config) as crawler:
        result = await crawler.arun(
            url="https://remoteok.com",
            config=CrawlerRunConfig()
        )
        print(result.markdown.fit_markdown)

Decodo handles proxy rotation at the endpoint level – each request through gate.decodo.com:7000 is automatically assigned a different IP, so there’s no rotation logic to add in your Crawl4AI setup.

An exception, however, is when the target depends on session continuity, like login forms or cart flows, where changing IPs mid-session will break the flow. In those cases, you may need to switch to sticky sessions. Check out our comprehensive guide on rotating proxies that covers when to use each.

For sites that go beyond IP tracking into browser fingerprinting and other anti-detection mechanisms, Crawl4AI already gives you two layers: enable_stealth handles common JavaScript checks, and UndetectedAdapter goes deeper into fingerprinting. But if that’s not enough, Decodo Site Unblocker provides server-side anti-fingerprinting that's worth checking out.

Integrating LLMs for intelligent data extraction

The selector-based extraction methods we've covered work well when a website follows a predictable structure. But when layouts change, maintaining those selectors becomes another task. Multiply that across several websites, and the work adds up quickly.

Simon Willison, co-creator of Django, made a similar observation in a 2025 blog post. He argued that turning unstructured content into structured data could be one of the most commercially valuable LLM applications.

Crawl4AI makes this possible through LLMExtractionStrategy. Instead of writing CSS selectors for every field, you describe the information you want and define the expected output using a Pydantic schema.

The model processes the content Crawl4AI extracts and returns structured data based on your schema. This reduces the custom parsing code you need, though you should still validate the results.

Input format matters, too. In Ryan Lee's 2025 NEXT-EVAL study, Gemini 2.5 produced a hallucination rate of 91.46% when processing slimmed HTML. Using a flat JSON representation reduced that figure to 3.05%, with an F1 score of 0.9567.

These results come from a specific web extraction benchmark, so they don't mean every structured format will produce the same improvement. Still, they show how much the way you prepare webpage content can affect extraction quality.

Crawl4AI's filtered Markdown is useful for this reason. It removes much of the page clutter before the content reaches the model, giving the LLM less irrelevant material to work through.

Of course, LLM extraction introduces another consideration: cost. Each request consumes tokens, and the total can grow quickly when you're processing hundreds or thousands of pages.

Which LLM should you use with Crawl4AI?

Choosing a model isn't just about finding the cheapest API. You also need to consider how reliably it follows your extraction schema and whether you're comfortable sending the data to an external provider.

There are three main factors to consider:

  • Token cost: How much you'll spend processing input and generating structured responses.
  • Schema compliance: How reliably the model returns the fields and data types you've requested.
  • Data privacy: Whether you can send the content to a hosted API or need it to stay within your infrastructure.

The table below gives you a starting point for comparing your options:

Model

Cost (input/output per 1M tokens)

Best for

Caveat

$2.00 / $10.00

Complex extraction tasks that require stronger reasoning

More expensive than smaller, lightweight models

$3.00 / $15.00

Detailed extraction instructions and complex records

Higher output token costs

$0.15 / $0.60 (off-peak) or $0.30 / $1.20 (peak)

Cost-sensitive extraction and large workloads

Pricing varies between peak and off-peak periods

N/A (self-hosted)

Private or offline extraction workflows

No per-token API fees, but hardware and electricity costs apply

$0.15 / $0.60

Fast, hosted inference for extraction tasks

Rate limits depend on the model and account plan

Note: Prices are in USD per 1 million input/output tokens, based on standard API rates as of November 2026. Check the provider pages for the latest rates.

Setting up LLM extraction

To use a hosted LLM with Crawl4AI, you'll need an API key from your chosen provider. We'll use DeepSeek V4.1 Flash for this example because it offers a relatively low-cost option for structured extraction.

Get an API key from your provider's dashboard. If you're following along with DeepSeek, see its official API documentation for instructions.

Create a .env file in your project's root directory and add your key:

DEEPSEEK_API_KEY=your_key_here

Then load the environment variables at the beginning of your Python script:

from dotenv import load_dotenv


load_dotenv()

If you're using another provider, such as OpenAI, replace DEEPSEEK_API_KEY with the appropriate environment variable, such as OPENAI_API_KEY. You'll also need to update the model identifier in the extraction configuration.

Define the extraction schema

Start with a Pydantic schema that describes the information you want to extract. Each field tells the LLM what to look for and what format to return.

For our RemoteOK example, we want the job title, company, location, salary, and relevant skills:

from typing import List, Optional
from pydantic import BaseModel, Field




class JobListing(BaseModel):
    title: str = Field(..., description="Job title")
    company: str = Field(..., description="Company name")
    location: str = Field(
        ..., description="Job location or 'Anywhere' if remote"
    )
    salary: Optional[str] = Field(
        None, description="Salary range if listed"
    )
    tags: List[str] = Field(
        default_factory=list,
        description="Tech stack and skills"
    )




class JobListings(BaseModel):
    jobs: List[JobListing] = Field(
        default_factory=list,
        description="All job listings extracted from the page"
    )

Notice that salary is optional. RemoteOK doesn't always display salary information, so we allow the field to be empty rather than requiring the model to provide a value that might not exist.

We've also added a JobListings model to hold multiple results. This matters because we're asking the LLM to extract all the jobs on the page, not just one.

Configure LLM extraction

Now we can connect the schema to LLMExtractionStrategy and pass it into CrawlerRunConfig.

import asyncio
import json
import os


from dotenv import load_dotenv
from crawl4ai import (
    AsyncWebCrawler,
    BrowserConfig,
    CrawlerRunConfig,
    CacheMode,
    LLMConfig
)
from crawl4ai.extraction_strategy import LLMExtractionStrategy




load_dotenv()




async def main():
    extraction_strategy = LLMExtractionStrategy(
        llm_config=LLMConfig(
            provider="deepseek/deepseek-flash",
            api_token=os.getenv("DEEPSEEK_API_KEY")
        ),
        schema=JobListings.model_json_schema(),
        extraction_type="schema",
        instruction=(
            "Extract all job listings from the page. "
            "For each job, return the title, company, location, "
            "salary range if available, and relevant skills. "
            "Do not invent missing information."
        ),
        input_format="markdown"
    )


    config = CrawlerRunConfig(
        extraction_strategy=extraction_strategy,
        cache_mode=CacheMode.BYPASS
    )


    async with AsyncWebCrawler(
        config=BrowserConfig(headless=True)
    ) as crawler:
        result = await crawler.arun(
            url="https://remoteok.com",
            config=config
        )


        if result.success and result.extracted_content:
            data = json.loads(result.extracted_content)
            print(json.dumps(data, indent=2))
        else:
            print(
                "Extraction failed:",
                result.error_message or "No data returned"
            )


    extraction_strategy.show_usage()




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

Here, LLMConfig specifies the model and API key, while LLMExtractionStrategy tells Crawl4AI how to extract the job information.

Instead of relying on CSS selectors, Crawl4AI sends the page's Markdown content to DeepSeek along with our schema and instructions. The model then returns structured JSON containing the extracted job listings.

We've also enabled CacheMode.BYPASS to fetch fresh page content and added show_usage() to display token consumption after the extraction. This is useful when comparing the cost of different models.

Running models locally with Ollama

You can also run LLM extraction locally with Ollama, without sending your page content to a third-party model provider.

First, make sure Ollama is installed, its local server is running, and you've downloaded the model you want to use. Then point LLMConfig to your local Ollama instance:

extraction_strategy = LLMExtractionStrategy(
    llm_config=LLMConfig(
        provider="ollama/llama3",
        api_token="no-token",
        base_url="http://localhost:11434"
    ),
    schema=JobListings.model_json_schema(),
    extraction_type="schema",
    instruction=(
        "Extract all job listings from the page, including "
        "title, company, location, salary if available, and tags."
    ),
    input_format="markdown"
)

Local extraction comes with its own trade-offs. You'll need enough memory and processing power to run your chosen model, and smaller local models may struggle with complicated extraction tasks. For sensitive data or workflows that need to run offline, that trade-off can be worthwhile.

Token limits and chunking

Large pages can contain more text than you want to send to an LLM in a single request. This becomes especially important when you're working with smaller models or processing several pages.

LLMExtractionStrategy supports automatic chunking to handle this. It splits longer content into smaller sections and can overlap adjacent chunks so the model doesn't lose important context between them.

You can control this behavior using chunk_token_threshold, overlap_rate, and apply_chunking.

For example, here's how to configure larger chunks with a 10% overlap:

extraction_strategy = LLMExtractionStrategy(
    llm_config=LLMConfig(
        provider="deepseek/deepseek-flash",
        api_token=os.getenv("DEEPSEEK_API_KEY")
    ),
    schema=JobListings.model_json_schema(),
    extraction_type="schema",
    instruction=(
        "Extract all job listings from the page, including "
        "title, company, location, salary if available, and tags."
    ),
    input_format="markdown",
    chunk_token_threshold=4096,
    overlap_rate=0.1,
    apply_chunking=True
)

Here, chunk_token_threshold=4096 sets the approximate maximum chunk size, while overlap_rate=0.1 retains some context between consecutive chunks.

Larger chunks may reduce API calls, but they also increase the amount of content processed in each request. Smaller chunks can be easier for lightweight models to handle, although they may separate information that belongs together.

Note: Keep apply_chunking=True for longer pages unless you've confirmed that the content comfortably fits within your model's context window. 

That covers the basics of LLM extraction with Crawl4AI. But if you're building a production RAG pipeline, data extraction is only part of the job.

Poor chunking, weak indexing, and inconsistent retrieval can affect result quality, even when the crawler works perfectly. Our guide on RAG with LlamaIndex and web scraping explains how to build a more reliable ingestion pipeline.

If you'd rather avoid managing dataset collection and preparation yourself, see how Decodo handles LLM training data.

Best practices for production crawlers

Production crawling is about maintaining stability under load, handling resistance from target sites, and using resources efficiently. These five practices address that directly.

1. Remove everything that doesn't serve the extraction

If the goal is text extraction, images, fonts, and stylesheets add unnecessary overhead.

Block non-essential resources at the browser level and run in headless mode by default. This reduces render time, memory usage, and per-page bandwidth. For large-scale URL discovery, use prefetch mode to skip Markdown generation and return only HTML and links.

Throughput improves because each page requires less processing.

2. Concurrency should follow memory limits

Crawl4AI's async model allows parallel execution, but each browser instance consumes RAM. Set concurrency based on available system memory. On constrained machines, high parallelism can exhaust resources before the crawl finishes.

The memory-adaptive dispatcher adjusts concurrency based on real-time memory usage, which makes it a safer default than fixed limits.

3. Add controlled delays between requests

A crawler that sends requests continuously at maximum speed is easy to detect.

Introduce randomized delays between requests, typically 2 to 5 seconds for sensitive targets. This reduces detection risk and prevents unnecessary load on the target server. Delays improve stability and reduce the chance of being blocked.

4. Design for failure and recovery

Failures are expected in long-running crawls. Without state persistence, a single interruption can invalidate hours of progress.

Persist crawl state after each URL so work is continuously saved, for example, using a state.json or similar checkpoint file. Resume functionality should pick up from the last completed step without duplication or data loss. This ensures the crawler can recover cleanly from crashes, restarts, or external interruptions.

Log each failure with the URL, timestamp, and error details. This creates a reliable audit trail for debugging and makes it easier to identify patterns in failed requests.

5. Respect target sites' systems

Responsible crawling reduces the risk of blocks and service disruption. Before crawling, check robots.txt, review the site's terms of service, and ensure request rates stay within what the server can handle, for example, by applying rate limiting in your request loop.

These are operational constraints, not suggestions. Ignoring them leads to blocked IPs and unstable pipelines.

6. Keep Crawl4AI updated and pin your dependencies

Crawl4AI is actively maintained, and some updates address security issues, not just add features.

For production projects, pin Crawl4AI to a version you've tested, such as crawl4ai==0.9.5. This keeps your environment consistent and prevents unexpected changes when you reinstall dependencies.

However, pinning shouldn't mean ignoring updates. Version 0.8.6 replaced a compromised dependency, while versions 0.9.4 and 0.9.5 addressed several disclosed security vulnerabilities.

Keep an eye on the official GitHub releases and review security updates as they're published. Test new versions before deploying them, but don't leave known vulnerabilities unpatched.

Self-hosted Crawl4AI vs. a managed crawl API

Should you run Crawl4AI yourself or use a managed crawling service? It depends on how much control you need and how much infrastructure you're willing to maintain.

Self-hosting makes sense when you want complete control over browser behavior, extraction strategies, and crawling logic. But if your goal is to collect hundreds or thousands of pages without managing browsers and proxies, a managed API can save considerable setup time.

For example, Decodo's /crawl endpoint handles URL discovery, page fetching, and extraction in a single managed job.

Here's how the options compare:

Feature

Crawl4AI (self-hosted)

Crawl4AI Cloud

Decodo Web Data API /crawl

Browser management

You run and maintain browsers

Managed by Crawl4AI

Managed by Decodo

Proxies and anti-bot handling

You configure proxies and browser settings

Managed infrastructure and proxy options

Built-in proxy management and automatic JavaScript retry

Page limits per crawl

Configurable, subject to your resources

Up to 500 pages through the /site endpoint

Up to 10,000 pages per crawl

Output formats

Markdown, HTML, and structured JSON

Markdown or HTML; JSON through extraction APIs

Markdown or HTML

Pricing model

Free library; infrastructure, proxies, and LLMs cost extra

Credit-based, with free and paid plans

Free and paid plans, with usage charged per scraped page

Best for

Custom workflows and maximum control

Hosted Crawl4AI workflows

Larger site-wide crawls without managing infrastructure

As of November 2026, Crawl4AI Cloud is available, with its /site endpoint supporting link discovery and crawling up to 500 pages per job. Its separate batch-job endpoint can process up to 10,000 URLs that you provide.

Decodo's /crawl takes a different approach. You supply a starting URL, and it follows links up to your chosen depth and page limit. It supports sitemap discovery, path filtering with select_paths, and webhooks that notify your application when a crawl finishes.

Results remain available for 24 hours after completion. You can also use Decodo's /map endpoint to identify relevant URLs before deciding which sections to crawl. See the /crawl documentation for the available parameters.

Ultimately, self-hosted Crawl4AI gives you flexibility, while managed services reduce the work involved in running and maintaining the crawling infrastructure.

Final thoughts

In this tutorial, you've moved from basic page crawling to structured, AI-ready data extraction. You've seen how Crawl4AI handles JavaScript rendering with Playwright, filters unnecessary content, and uses LLMExtractionStrategy when CSS selectors aren't enough.

However, reliable website access can still be challenging. Protected sites may block repeated requests or return incomplete data, making extraction failures difficult to detect. Pairing Crawl4AI with Decodo's 115M+ residential proxy network can help improve access to these sites.

If you'd rather avoid managing browsers and crawling infrastructure yourself, you can also run the crawl as a managed job using Decodo's Web Data API.

Fetch what Crawl4AI can't

Web Data API handles JavaScript rendering, proxy rotation, and bot protection in one request.

Share article:

About the author

Justinas Tamasevicius

Director of Engineering

Justinas Tamaševičius is Director of Engineering with over two decades of expertise in software development. What started as a self-taught passion during his school years has evolved into a distinguished career spanning backend engineering, system architecture, and infrastructure development.

Connect with Justinas via LinkedIn.

All information on Decodo Blog is provided on an as is basis and for informational purposes only. We make no representation and disclaim all liability with respect to your use of any information contained on Decodo Blog or any third-party websites that may belinked therein.

Frequently asked questions

What is Crawl4AI used for?

Crawl4AI collects website content and turns it into structured, AI-ready data. It can render JavaScript-heavy pages, extract specific fields, convert HTML to Markdown, and follow links across multiple pages. This makes it useful for web scraping, dataset creation, AI agents, and retrieval-augmented generation (RAG) pipelines.

Is Crawl4AI free to use?

Yes. The self-hosted Crawl4AI library is free and open-source under the Apache License 2.0. 

Crawl4AI also offers a separate hosted Cloud service with a credit-based free tier and paid plans. If you use an external LLM for extraction, the model provider may charge you separately.

Does Crawl4AI use Playwright?

Yes. Crawl4AI uses Playwright for browser automation, letting it render JavaScript, interact with dynamic elements, and extract content not available in the initial HTML response. It builds on those browser capabilities by adding crawling strategies, content filtering, Markdown generation, and structured extraction.

What makes Crawl4AI better than Scrapy or Selenium?

It depends on what you're building. Crawl4AI is particularly convenient for AI-focused scraping because it combines browser rendering, Markdown conversion, and LLM extraction in one asynchronous framework.

Scrapy suits large-scale crawling and request management, while Selenium is useful for browser automation and interactive testing. Both can support scraping workflows, but preparing their output for LLMs generally requires additional processing.

Do I need an API key to use Crawl4AI?

No. Basic crawling, CSS and XPath extraction, Markdown generation, and deep crawling work without an external API key when you run Crawl4AI locally.

You'll need credentials if you use a hosted LLM provider or Crawl4AI Cloud. For LLM extraction without an external API key, you can run a compatible model locally using Ollama.

Can I use Crawl4AI with a local LLM?

Yes. Crawl4AI supports local LLM extraction through Ollama, so you can process scraped content without sending it to an external model provider.

You won't pay per-token API fees, but extraction speed and memory requirements depend on your model and hardware. A GPU can improve performance, though Ollama also supports CPU execution.

Is Crawl4AI safe to use?

Yes, as long as you follow appropriate security practices. Keep Crawl4AI updated, review its dependencies, validate URLs before crawling, and avoid exposing an unsecured crawler server to the internet.

Does Crawl4AI have an MCP server?

Yes. Crawl4AI's official self-hosted server supports the Model Context Protocol (MCP), allowing AI assistants and compatible applications to access its crawling capabilities directly.

The server provides tools to crawl pages, generate Markdown, extract HTML, capture screenshots, and create PDFs. You can find the available tools and connection methods in the official Crawl4AI MCP documentation. For a broader introduction, see our guide to setting up an MCP server.

How do I handle sites that block my IP?

You need proxies. For straightforward targets, datacenter proxies offer a fast, cost-effective option. More heavily protected targets may benefit from residential proxies, which route traffic through real residential IP addresses.

For more demanding targets, Decodo Site Unblocker offers managed request handling, including proxy rotation, JavaScript rendering, and CAPTCHA handling.

Playwright logo and title 'Playwright' showing subtitle 'Web Scraping Tutorial' on a dark dotted background

Playwright Web Scraping: A Practical Tutorial

Web scraping can feel like directing a play without a script – unpredictable and chaotic. That’s where Playwright steps in: a powerful, headless browser automation tool that makes scraping modern, dynamic websites smoother than ever. In this practical tutorial, you’ll learn how to use Playwright to reliably extract data from any web page.

Dashboard line chart showing purple trend, with tabs 'Last 24 hours  Last week  Last month  Custom' on dark textured backdrop

Mastering Scrapy for Scalable Python Web Scraping: A Practical Guide

Scrapy is a powerful web scraping framework available in Python. Its asynchronous architecture makes it faster than sequential scrapers built with Requests or Beautiful Soup, and it includes everything needed for production-ready scraping: spiders, items, pipelines, throttling, retries, data export, and middleware. In this guide, you'll learn how to set up Scrapy, build and customize spiders, handle pagination, structure and store data, extend Scrapy with middlewares and proxies, and apply best practices for scraping at scale.

Python logo rising from a bowl beside a spoon in neon magenta on dark background

Beautiful Soup Web Scraping: How to Parse Scraped HTML with Python

Web scraping with Python is a powerful technique for extracting valuable data from the web, enabling automation, analysis, and integration across various domains. Using libraries like Beautiful Soup and Requests, developers can efficiently parse HTML and XML documents, transforming unstructured web data into structured formats for further use. This guide explores essential tools and techniques to navigate the vast web and extract meaningful insights effortlessly.

© 2018-2026 decodo.com (formerly smartproxy.com). All Rights Reserved