迁移与 API 参考(3/3)
The AsyncWebCrawler is the core class for asynchronous web crawling in Crawl4AI. You typically create it once, optionally customize it with a BrowserConfig (e.g., headless, user agent), then run multiple arun() calls with different CrawlerRunConfig objects.
Recommended usage:
1. Create a BrowserConfig for global browser settings.
2. Instantiate AsyncWebCrawler(config=browser_config).
3. Use the crawler in an async context manager (async with) or manage start/close manually.
4. Call arun(url, config=crawler_run_config) for each page you want.
1. Constructor Overview
class AsyncWebCrawler:
def __init__(
self,
crawler_strategy: Optional[AsyncCrawlerStrategy] = None,
config: Optional[BrowserConfig] = None,
always_bypass_cache: bool = False, # deprecated
always_by_pass_cache: Optional[bool] = None, # also deprecated
base_directory: str = ...,
thread_safe: bool = False,
**kwargs,
):
"""
Create an AsyncWebCrawler instance.
Args:
crawler_strategy:
(Advanced) Provide a custom crawler strategy if needed.
config:
A BrowserConfig object specifying how the browser is set up.
always_bypass_cache:
(Deprecated) Use CrawlerRunConfig.cache_mode instead.
base_directory:
Folder for storing caches/logs (if relevant).
thread_safe:
If True, attempts some concurrency safeguards. Usually False.
**kwargs:
Additional legacy or debugging parameters.
"""
)
### Typical Initialization
```python
from crawl4ai import AsyncWebCrawler, BrowserConfig
browser_cfg = BrowserConfig(
browser_type="chromium",
headless=True,
verbose=True
)
crawler = AsyncWebCrawler(config=browser_cfg)
Notes:
- Legacy parameters like
always_bypass_cacheremain for backward compatibility, but prefer to set caching inCrawlerRunConfig.
2. Lifecycle: Start/Close or Context Manager
2.1 Context Manager (Recommended)
async with AsyncWebCrawler(config=browser_cfg) as crawler:
result = await crawler.arun("https://example.com")
# The crawler automatically starts/closes resources
When the async with block ends, the crawler cleans up (closes the browser, etc.).
2.2 Manual Start & Close
crawler = AsyncWebCrawler(config=browser_cfg)
await crawler.start()
result1 = await crawler.arun("https://example.com")
result2 = await crawler.arun("https://another.com")
await crawler.close()
Use this style if you have a long-running application or need full control of the crawler’s lifecycle.
3. Primary Method: arun()
async def arun(
self,
url: str,
config: Optional[CrawlerRunConfig] = None,
# Legacy parameters for backward compatibility...
) -> RunManyReturn:
...
3.1 New Approach
You pass a CrawlerRunConfig object that sets up everything about a crawl—content filtering, caching, session reuse, JS code, screenshots, etc.
import asyncio
from crawl4ai import CrawlerRunConfig, CacheMode
run_cfg = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
css_selector="main.article",
word_count_threshold=10,
screenshot=True
)
async with AsyncWebCrawler(config=browser_cfg) as crawler:
result = await crawler.arun("https://example.com/news", config=run_cfg)
print("Crawled HTML length:", len(result.cleaned_html))
if result.screenshot:
print("Screenshot base64 length:", len(result.screenshot))
3.2 Legacy Parameters Still Accepted
For backward compatibility, arun() can still accept direct arguments like css_selector=..., word_count_threshold=..., etc., but we strongly advise migrating them into a CrawlerRunConfig.
4. Batch Processing: arun_many()
async def arun_many(
self,
urls: List[str],
config: Optional[CrawlerRunConfig] = None,
# Legacy parameters maintained for backwards compatibility...
) -> RunManyReturn:
"""
Process multiple URLs with intelligent rate limiting and resource monitoring.
"""
4.1 Resource-Aware Crawling
The arun_many() method now uses an intelligent dispatcher that:
- Monitors system memory usage
- Implements adaptive rate limiting
- Provides detailed progress monitoring
- Manages concurrent crawls efficiently
4.2 Example Usage
Check page Multi-url Crawling for a detailed example of how to use arun_many().
### 4.3 Key Features
1. **Rate Limiting**
- Automatic delay between requests
- Exponential backoff on rate limit detection
- Domain-specific rate limiting
- Configurable retry strategy
2. **Resource Monitoring**
- Memory usage tracking
- Adaptive concurrency based on system load
- Automatic pausing when resources are constrained
3. **Progress Monitoring**
- Detailed or aggregated progress display
- Real-time status updates
- Memory usage statistics
4. **Error Handling**
- Graceful handling of rate limits
- Automatic retries with backoff
- Detailed error reporting
---
## 5. `CrawlResult` Output
Each `arun()` returns a **`CrawlResult`** containing:
- `url`: Final URL (if redirected).
- `html`: Original HTML.
- `cleaned_html`: Sanitized HTML.
- `markdown_v2`: Removed in v0.5. Accessing it raises `AttributeError`; use `markdown`.
- `extracted_content`: If an extraction strategy was used (JSON for CSS/LLM strategies).
- `screenshot`, `pdf`: If screenshots/PDF requested.
- `media`, `links`: Information about discovered images/links.
- `success`, `error_message`: Status info.
For details, see [CrawlResult doc](./crawl-result.md).
---
## 6. Quick Example
Below is an example hooking it all together:
```python
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
from crawl4ai import JsonCssExtractionStrategy
import json
async def main():
# 1. Browser config
browser_cfg = BrowserConfig(
browser_type="firefox",
headless=False,
verbose=True
)
# 2. Run config
schema = {
"name": "Articles",
"baseSelector": "article.post",
"fields": [
{
"name": "title",
"selector": "h2",
"type": "text"
},
{
"name": "url",
"selector": "a",
"type": "attribute",
"attribute": "href"
}
]
}
run_cfg = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
extraction_strategy=JsonCssExtractionStrategy(schema),
word_count_threshold=15,
remove_overlay_elements=True,
wait_for="css:.post" # Wait for posts to appear
)
async with AsyncWebCrawler(config=browser_cfg) as crawler:
result = await crawler.arun(
url="https://example.com/blog",
config=run_cfg
)
if result.success:
print("Cleaned HTML length:", len(result.cleaned_html))
if result.extracted_content:
articles = json.loads(result.extracted_content)
print("Extracted articles:", articles[:2])
else:
print("Error:", result.error_message)
asyncio.run(main())
Explanation:
- We define a
BrowserConfigwith Firefox, no headless, andverbose=True. - We define a
CrawlerRunConfigthat bypasses cache, uses a CSS extraction schema, has aword_count_threshold=15, etc. - We pass them to
AsyncWebCrawler(config=...)andarun(url=..., config=...).
7. Best Practices & Migration Notes
1. Use BrowserConfig for global settings about the browser’s environment.
2. Use CrawlerRunConfig for per-crawl logic (caching, content filtering, extraction strategies, wait conditions).
3. Avoid legacy parameters like css_selector or word_count_threshold directly in arun(). Instead:
run_cfg = CrawlerRunConfig(css_selector=".main-content", word_count_threshold=20)
result = await crawler.arun(url="...", config=run_cfg)
4. Context Manager usage is simplest unless you want a persistent crawler across many calls.
8. Summary
AsyncWebCrawler is your entry point to asynchronous crawling:
- Constructor accepts
BrowserConfig(or defaults). arun(url, config=CrawlerRunConfig)is the main method for single-page crawls.arun_many(urls, config=CrawlerRunConfig)handles concurrency across multiple URLs.- For advanced lifecycle control, use
start()andclose()explicitly.
Migration:
- If you used
AsyncWebCrawler(browser_type="chromium", css_selector="..."), move browser settings toBrowserConfig(...)and content/crawl logic toCrawlerRunConfig(...).
This modular approach ensures your code is clean, scalable, and easy to maintain. For any advanced or rarely used parameters, see the BrowserConfig docs.
In Crawl4AI’s latest configuration model, nearly all parameters that once went directly to arun() are now part of CrawlerRunConfig. When calling arun(), you provide:
await crawler.arun(
url="https://example.com",
config=my_run_config
)
Below is an organized look at the parameters that can go inside CrawlerRunConfig, divided by their functional areas. For Browser settings (e.g., headless, browser_type), see BrowserConfig.
1. Core Usage
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
async def main():
run_config = CrawlerRunConfig(
verbose=True, # Detailed logging
cache_mode=CacheMode.ENABLED, # Use normal read/write cache
check_robots_txt=True, # Respect robots.txt rules
# ... other parameters
)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://example.com",
config=run_config
)
# Check if blocked by robots.txt
if not result.success and result.status_code == 403:
print(f"Error: {result.error_message}")
Key Fields:
- verbose=True logs each crawl step.
- cache_mode decides how to read/write the local crawl cache.
2. Cache Control
cache_mode (default: CacheMode.ENABLED)
Use a built-in enum from CacheMode:
ENABLED: Normal caching—reads if available, writes if missing.DISABLED: No caching—always refetch pages.READ_ONLY: Reads from cache only; no new writes.WRITE_ONLY: Writes to cache but doesn’t read existing data.BYPASS: Skips reading cache for this crawl (though it might still write if set up that way).
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS
)
Cache modes:
CacheMode.BYPASS— Skip cache entirely; always fetch fresh, write result to cache.CacheMode.DISABLED— No caching at all; don't read or write.CacheMode.WRITE_ONLY— Never read from cache, but write results.CacheMode.READ_ONLY— Read from cache if available, never write.
3. Content Processing & Selection
3.1 Text Processing
run_config = CrawlerRunConfig(
word_count_threshold=10, # Ignore text blocks <10 words
only_text=False, # If True, tries to remove non-text elements
keep_data_attributes=False # Keep or discard data-* attributes
)
3.2 Content Selection
run_config = CrawlerRunConfig(
css_selector=".main-content", # Focus on .main-content region only
excluded_tags=["form", "nav"], # Remove entire tag blocks
remove_forms=True, # Specifically strip <form> elements
remove_overlay_elements=True, # Attempt to remove modals/popups
)
3.3 Link Handling
run_config = CrawlerRunConfig(
exclude_external_links=True, # Remove external links from final content
exclude_social_media_links=True, # Remove links to known social sites
exclude_domains=["ads.example.com"], # Exclude links to these domains
exclude_social_media_domains=["facebook.com","twitter.com"], # Extend the default list
)
3.4 Media Filtering
run_config = CrawlerRunConfig(
exclude_external_images=True # Strip images from other domains
)
4. Page Navigation & Timing
4.1 Basic Browser Flow
run_config = CrawlerRunConfig(
wait_for="css:.dynamic-content", # Wait for .dynamic-content
delay_before_return_html=2.0, # Wait 2s before capturing final HTML
page_timeout=60000, # Navigation & script timeout (ms)
)
Key Fields:
wait_for:"css:selector"or-
"js:() => boolean"e.g.js:() => document.querySelectorAll('.item').length > 10. -
mean_delay&max_range: define random delays forarun_many()calls. semaphore_count: concurrency limit when crawling multiple URLs.
4.2 JavaScript Execution
run_config = CrawlerRunConfig(
js_code=[
"window.scrollTo(0, document.body.scrollHeight);",
"document.querySelector('.load-more')?.click();"
],
js_only=False
)
js_codecan be a single string or a list of strings.js_only=Truemeans “I’m continuing in the same session with new JS steps, no new full navigation.”
4.3 Anti-Bot
run_config = CrawlerRunConfig(
magic=True,
simulate_user=True,
override_navigator=True
)
magic=Truetries multiple stealth features.simulate_user=Truemimics mouse movements or random delays.override_navigator=Truefakes some navigator properties (like user agent checks).
5. Session Management
session_id:
run_config = CrawlerRunConfig(
session_id="my_session123"
)
If re-used in subsequent arun() calls, the same tab/page context is continued (helpful for multi-step tasks or stateful browsing).
6. Screenshot, PDF & Media Options
run_config = CrawlerRunConfig(
screenshot=True, # Grab a screenshot as base64
screenshot_wait_for=1.0, # Wait 1s before capturing
pdf=True, # Also produce a PDF
image_description_min_word_threshold=5, # If analyzing alt text
image_score_threshold=3, # Filter out low-score images
)
Where they appear:
- result.screenshot → Base64 screenshot string.
- result.pdf → Byte array with PDF data.
7. Extraction Strategy
For advanced data extraction (CSS/LLM-based), set extraction_strategy:
run_config = CrawlerRunConfig(
extraction_strategy=my_css_or_llm_strategy
)
The extracted data will appear in result.extracted_content.
8. Comprehensive Example
Below is a snippet combining many parameters:
import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
from crawl4ai import JsonCssExtractionStrategy
async def main():
# Example schema
schema = {
"name": "Articles",
"baseSelector": "article.post",
"fields": [
{"name": "title", "selector": "h2", "type": "text"},
{"name": "link", "selector": "a", "type": "attribute", "attribute": "href"}
]
}
run_config = CrawlerRunConfig(
# Core
verbose=True,
cache_mode=CacheMode.ENABLED,
check_robots_txt=True, # Respect robots.txt rules
# Content
word_count_threshold=10,
css_selector="main.content",
excluded_tags=["nav", "footer"],
exclude_external_links=True,
# Page & JS
js_code="document.querySelector('.show-more')?.click();",
wait_for="css:.loaded-block",
page_timeout=30000,
# Extraction
extraction_strategy=JsonCssExtractionStrategy(schema),
# Session
session_id="persistent_session",
# Media
screenshot=True,
pdf=True,
# Anti-bot
simulate_user=True,
magic=True,
)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun("https://example.com/posts", config=run_config)
if result.success:
print("HTML length:", len(result.cleaned_html))
print("Extraction JSON:", result.extracted_content)
if result.screenshot:
print("Screenshot length:", len(result.screenshot))
if result.pdf:
print("PDF bytes length:", len(result.pdf))
else:
print("Error:", result.error_message)
if __name__ == "__main__":
asyncio.run(main())
What we covered:
1. Crawling the main content region, ignoring external links. 2. Running JavaScript to click “.show-more”. 3. Waiting for “.loaded-block” to appear. 4. Generating a screenshot & PDF of the final page. 5. Extracting repeated “article.post” elements with a CSS-based extraction strategy.
9. Best Practices
1. Use BrowserConfig for global browser settings (headless, user agent).
2. Use CrawlerRunConfig to handle the specific crawl needs: content filtering, caching, JS, screenshot, extraction, etc.
3. Keep your parameters consistent in run configs—especially if you’re part of a large codebase with multiple crawls.
4. Limit large concurrency (semaphore_count) if the site or your system can’t handle it.
5. For dynamic pages, set js_code or scan_full_page so you load all content.
10. Conclusion
All parameters that used to be direct arguments to arun() now belong in CrawlerRunConfig. This approach:
- Makes code clearer and more maintainable.
- Minimizes confusion about which arguments affect global vs. per-crawl behavior.
- Allows you to create reusable config objects for different pages or tasks.
For a full reference, check out the CrawlerRunConfig Docs.
Happy crawling with your structured, flexible config approach!
Note: This function is very similar to
arun()but focused on concurrent or batch crawling. If you’re unfamiliar witharun()usage, please read that doc first, then review this for differences.
Function Signature
async def arun_many(
urls: Union[List[str], List[Any]],
config: Optional[Union[CrawlerRunConfig, List[CrawlerRunConfig]]] = None,
dispatcher: Optional[BaseDispatcher] = None,
...
) -> RunManyReturn:
"""
Crawl multiple URLs concurrently or in batches.
:param urls: A list of URLs (or tasks) to crawl.
:param config: (Optional) Either:
- A single `CrawlerRunConfig` applying to all URLs
- A list of `CrawlerRunConfig` objects with url_matcher patterns
:param dispatcher: (Optional) A concurrency controller (e.g. MemoryAdaptiveDispatcher).
...
:return: RunManyReturn containing either a list of `CrawlResult` objects or an async generator if streaming is enabled.
"""
Differences from arun()
1. Multiple URLs:
- Instead of crawling a single URL, you pass a list of them (strings or tasks).
- The function returns
RunManyReturnwhich contains either a list ofCrawlResultor an async generator if streaming is enabled.
2. Concurrency & Dispatchers:
dispatcherparam allows advanced concurrency control.- If omitted, a default dispatcher (like
MemoryAdaptiveDispatcher) is used internally. - Dispatchers handle concurrency, rate limiting, and memory-based adaptive throttling (see Multi-URL Crawling).
3. Streaming Support:
- Enable streaming by setting
stream=Truein yourCrawlerRunConfig. - When streaming, use
async forto process results as they become available. - Ideal for processing large numbers of URLs without waiting for all to complete.
4. Parallel Execution**:
arun_many()can run multiple requests concurrently under the hood.- Each
CrawlResultmight also include adispatch_resultwith concurrency details (like memory usage, start/end times).
Basic Example (Batch Mode)
# Minimal usage: The default dispatcher will be used
results = await crawler.arun_many(
urls=["https://site1.com", "https://site2.com"],
config=CrawlerRunConfig(stream=False) # Default behavior
)
for res in results:
if res.success:
print(res.url, "crawled OK!")
else:
print("Failed:", res.url, "-", res.error_message)
Streaming Example
config = CrawlerRunConfig(
stream=True, # Enable streaming mode
cache_mode=CacheMode.BYPASS
)
# Process results as they complete
async for result in await crawler.arun_many(
urls=["https://site1.com", "https://site2.com", "https://site3.com"],
config=config
):
if result.success:
print(f"Just completed: {result.url}")
# Process each result immediately
process_result(result)
With a Custom Dispatcher
dispatcher = MemoryAdaptiveDispatcher(
memory_threshold_percent=70.0,
max_session_permit=10
)
results = await crawler.arun_many(
urls=["https://site1.com", "https://site2.com", "https://site3.com"],
config=my_run_config,
dispatcher=dispatcher
)
URL-Specific Configurations
Instead of using one config for all URLs, provide a list of configs with url_matcher patterns:
from crawl4ai import CrawlerRunConfig, MatchMode
from crawl4ai.processors.pdf import PDFContentScrapingStrategy
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
from crawl4ai.content_filter_strategy import PruningContentFilterLXML
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator
# PDF files - specialized extraction
pdf_config = CrawlerRunConfig(
url_matcher="*.pdf",
scraping_strategy=PDFContentScrapingStrategy()
)
# Blog/article pages - content filtering
blog_config = CrawlerRunConfig(
url_matcher=["*/blog/*", "*/article/*", "*python.org*"],
markdown_generator=DefaultMarkdownGenerator(
content_filter=PruningContentFilterLXML(threshold=0.48)
)
)
# Dynamic pages - JavaScript execution
github_config = CrawlerRunConfig(
url_matcher=lambda url: 'github.com' in url,
js_code="window.scrollTo(0, 500);"
)
# API endpoints - JSON extraction
api_config = CrawlerRunConfig(
url_matcher=lambda url: 'api' in url or url.endswith('.json'),
# Custome settings for JSON extraction
)
# Default fallback config
default_config = CrawlerRunConfig() # No url_matcher means it never matches except as fallback
# Pass the list of configs - first match wins!
results = await crawler.arun_many(
urls=[
"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", # → pdf_config
"https://blog.python.org/", # → blog_config
"https://github.com/microsoft/playwright", # → github_config
"https://httpbin.org/json", # → api_config
"https://example.com/" # → default_config
],
config=[pdf_config, blog_config, github_config, api_config, default_config]
)
URL Matching Features:
- String patterns: "*.pdf", "*/blog/*", "*python.org*"
- Function matchers: lambda url: 'api' in url
- Mixed patterns: Combine strings and functions with MatchMode.OR or MatchMode.AND
- First match wins: Configs are evaluated in order
Key Points:
- Each URL is processed by the same or separate sessions, depending on the dispatcher’s strategy.
- dispatch_result in each CrawlResult (if using concurrency) can hold memory and timing info.
- If you need to handle authentication or session IDs, pass them in each individual task or within your run config.
- Important: Always include a default config (without url_matcher) as the last item if you want to handle all URLs. Otherwise, unmatched URLs will fail.
Return Value
Returns a RunManyReturn object which contains either a list of CrawlResult objects, or an async generator if streaming is enabled. You can iterate to check result.success or read each item’s extracted_content, markdown, or dispatch_result.
Dispatcher Reference
MemoryAdaptiveDispatcher: Dynamically manages concurrency based on system memory usage.SemaphoreDispatcher: Fixed concurrency limit, simpler but less adaptive.
For advanced usage or custom settings, see Multi-URL Crawling with Dispatchers.
Common Pitfalls
1. Large Lists: If you pass thousands of URLs, be mindful of memory or rate-limits. A dispatcher can help.
2. Session Reuse: If you need specialized logins or persistent contexts, ensure your dispatcher or tasks handle sessions accordingly.
3. Error Handling: Each CrawlResult might fail for different reasons—always check result.success or the error_message before proceeding.
Conclusion
Use arun_many() when you want to crawl multiple URLs simultaneously or in controlled parallel tasks. If you need advanced concurrency features (like memory-based adaptive throttling or complex rate-limiting), provide a dispatcher. Each result is a standard CrawlResult, possibly augmented with concurrency stats (dispatch_result) for deeper inspection. For more details on concurrency logic and dispatchers, see the Advanced Multi-URL Crawling docs.
This guide helps you upgrade from v0.7.x to v0.8.0, with special attention to breaking changes and security updates.
Quick Summary
| Change | Impact | Action Required |
|---|---|---|
| Hooks disabled by default | Docker API users with hooks | Set CRAWL4AI_HOOKS_ENABLED=true |
| file:// URLs blocked | Docker API users reading local files | Use Python library directly |
| Security fixes | All Docker API users | Update immediately |
Step 1: Update the Package
PyPI Installation
pip install --upgrade crawl4ai
Docker Installation
docker pull unclecode/crawl4ai:latest
# or
docker pull unclecode/crawl4ai:0.8.0
From Source
git pull origin main
pip install -e .
Step 2: Check for Breaking Changes
Are You Affected?
You ARE affected if you:
- Use the Docker API deployment
- Use the hooks parameter in /crawl requests
- Use file:// URLs via API endpoints
You are NOT affected if you:
- Only use Crawl4AI as a Python library
- Don't use hooks in your API calls
- Don't use file:// URLs via the API
Step 3: Migrate Hooks Usage
Before v0.8.0
Hooks worked by default:
# This worked without any configuration
curl -X POST http://localhost:11235/crawl \
-H "Content-Type: application/json" \
-d '{
"urls": ["https://example.com"],
"hooks": {
"code": {
"on_page_context_created": "async def hook(page, context, **kwargs):\n await context.add_cookies([...])\n return page"
}
}
}'
After v0.8.0
You must explicitly enable hooks:
Option A: Environment Variable (Recommended)
# In your Docker run command or docker-compose.yml
export CRAWL4AI_HOOKS_ENABLED=true
# docker-compose.yml
services:
crawl4ai:
image: unclecode/crawl4ai:0.8.0
environment:
- CRAWL4AI_HOOKS_ENABLED=true
Option B: For Kubernetes
env:
- name: CRAWL4AI_HOOKS_ENABLED
value: "true"
Security Warning
Only enable hooks if: - You trust all users who can access the API - The API is not exposed to the public internet - You have other authentication/authorization in place
Step 4: Migrate file:// URL Usage
Before v0.8.0
# This worked via API
curl -X POST http://localhost:11235/execute_js \
-d '{"url": "file:///var/data/page.html", "scripts": ["document.title"]}'
After v0.8.0
Option A: Use the Python Library Directly
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async def process_local_file():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="file:///var/data/page.html",
config=CrawlerRunConfig(js_code=["document.title"])
)
return result
Option B: Use raw: Protocol for HTML Content
If you have the HTML content, you can still use the API:
# Read file content and send as raw:
HTML_CONTENT=$(cat /var/data/page.html)
curl -X POST http://localhost:11235/html \
-H "Content-Type: application/json" \
-d "{\"url\": \"raw:$HTML_CONTENT\"}"
Option C: Create a Preprocessing Service
# preprocessing_service.py
from fastapi import FastAPI
from crawl4ai import AsyncWebCrawler
app = FastAPI()
@app.post("/process-local")
async def process_local(file_path: str):
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(url=f"file://{file_path}")
return result.model_dump()
Step 5: Review Security Configuration
Recommended Production Settings
# config.yml
security:
enabled: true
jwt_enabled: true
https_redirect: true # If behind HTTPS proxy
trusted_hosts:
- "your-domain.com"
- "api.your-domain.com"
Environment Variables
# Required for JWT authentication
export SECRET_KEY="your-secure-random-key-minimum-32-characters"
# Only if you need hooks
export CRAWL4AI_HOOKS_ENABLED=true
Generate a Secure Secret Key
import secrets
print(secrets.token_urlsafe(32))
Step 6: Test Your Integration
Quick Validation Script
import asyncio
import aiohttp
async def test_upgrade():
base_url = "http://localhost:11235"
# Test 1: Basic crawl should work
async with aiohttp.ClientSession() as session:
async with session.post(
f"{base_url}/crawl",
json={"urls": ["https://example.com"]}
) as resp:
assert resp.status == 200, "Basic crawl failed"
print("✓ Basic crawl works")
# Test 2: Hooks should be blocked (unless enabled)
async with aiohttp.ClientSession() as session:
async with session.post(
f"{base_url}/crawl",
json={
"urls": ["https://example.com"],
"hooks": {"code": {"on_page_context_created": "async def hook(page, context, **kwargs): return page"}}
}
) as resp:
if resp.status == 403:
print("✓ Hooks correctly blocked (default)")
elif resp.status == 200:
print("! Hooks enabled - ensure this is intentional")
# Test 3: file:// should be blocked
async with aiohttp.ClientSession() as session:
async with session.post(
f"{base_url}/execute_js",
json={"url": "file:///etc/passwd", "scripts": ["1"]}
) as resp:
assert resp.status == 400, "file:// should be blocked"
print("✓ file:// URLs correctly blocked")
asyncio.run(test_upgrade())
Troubleshooting
"Hooks are disabled" Error
Symptom: API returns 403 with "Hooks are disabled"
Solution: Set CRAWL4AI_HOOKS_ENABLED=true if you need hooks
"URL must start with http://, https://" Error
Symptom: API returns 400 when using file:// URLs
Solution: Use Python library directly or raw: protocol
Authentication Errors After Enabling JWT
Symptom: API returns 401 Unauthorized
Solution:
1. Get a token: POST /token with your email
2. Include token in requests: Authorization: Bearer <token>
Rollback Plan
If you need to rollback:
# PyPI
pip install crawl4ai==0.7.6
# Docker
docker pull unclecode/crawl4ai:0.7.6
Warning: Rolling back re-exposes the security vulnerabilities. Only do this temporarily while fixing integration issues.
Getting Help
- GitHub Issues: github.com/unclecode/crawl4ai/issues
- Security Issues: See SECURITY.md
- Documentation: docs.crawl4ai.com
Changelog Reference
For complete list of changes, see: - Release Notes v0.8.0 - CHANGELOG.md
