how do i use crawl4ai?
- User
how do i use crawl4ai?
Assistant
how do i use crawl4ai?
To use Crawl4AI for web crawling and AI-friendly data extraction, follow these steps:
Python Installation
Install via pip with required dependencies:
pip install "crawl4ai @ git+https://github.com/unclecode/crawl4ai.git" transformers torch nltk
Set your OpenAI API key for LLM-based extraction:
export OPENAI_API_KEY='your_api_key_here'
[3][7]
Docker Setup
Run the Docker image with environment variables:
docker run -p 11235:11235 \
-e OPENAI_API_KEY=<your-key> \
-e MAX_CONCURRENT_TASKS=5 \
pondhouse/crawl4ai:beta-1
[1]
Use AsyncWebCrawler for asynchronous crawling:
import asyncio
from crawl4ai import AsyncWebCrawler
async def main():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(url="https://example.com")
print(result.markdown[:300]) # Print first 300 chars of Markdown
asyncio.run(main())
[2][4]
curl -X POST 'http://localhost:11235/crawl' \
-H 'Content-Type: application/json' \
-d '{"urls": "https://example.com"}'
Returns a task_id for tracking[1].curl 'http://localhost:11235/task/<task_id>'
[1]Customize browser behavior and crawl settings:
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
async def main():
browser_conf = BrowserConfig(
headless=True, # Run in headless mode
browser_type="chromium",
user_agent="custom-agent"
)
run_conf = CrawlerRunConfig(
cache_mode="BYPASS", # Bypass cache for fresh content
page_timeout=30000 # 30-second page load timeout
)
async with AsyncWebCrawler(config=browser_conf) as crawler:
result = await crawler.arun(
url="https://example.com",
config=run_conf
)
print(result.markdown)
[2][4]
Crawl pages with JavaScript-triggered content:
# Reuse session to click "Next Page" buttons
result = await crawler.arun(
url="https://example.com/pagination",
js_code="document.querySelector('.next-page').click()",
js_only=True # Continue existing session
)
[2]
Use LLM-based extraction for schema-defined data:
from crawl4ai.extraction_strategy import LLMExtractionStrategy
from pydantic import BaseModel
class ModelFee(BaseModel):
model_name: str
input_fee: str
output_fee: str
async def main():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url='https://openai.com/api/pricing/',
extraction_strategy=LLMExtractionStrategy(
provider="openai/gpt-4o",
api_token=os.getenv('OPENAI_API_KEY'),
schema=ModelFee.schema(),
instruction="Extract model fees in JSON format..."
)
)
print(result.extracted_content)
[7]
| Feature | Description |
|---|---|
| Asynchronous Crawling | Handle multiple requests concurrently for high performance[1][4]. |
| LLM Integration | Generate clean Markdown/JSON for RAG pipelines or direct LLM processing[4][6]. |
| Anti-Detection | Simulate human behavior, override navigator properties, and use proxies[1][7]. |
| Media Extraction | Capture images, videos, and metadata from crawled pages[3][7]. |
For detailed documentation, visit Crawl4AI Docs[4][4].