Crawl4AI 操作手册(v0.9.5 实测)
Crawl4AI 0.9.5 实测手册:Docker 部署的三条硬约束、REST 端点全表、Markdown 生成与内容过滤器、结构化抽取与缓存策略,逐条标注实测。
依据 https://docs.crawl4ai.com/ (v0.9.x)整理,并结合本机实际部署逐条验证。 标注说明:【实测】= 在本机 0.9.5 实例上跑通;【文档】= 官方文档描述,本机未逐一验证。
0. 本机环境事实
| 项目 | 值 |
|---|---|
| 镜像 | unclecode/crawl4ai:latest,实际版本 0.9.5 |
| 访问地址 | http://localhost:11235 |
| Playground | http://localhost:11235/playground/ |
| 鉴权 | Authorization: Bearer <CRAWL4AI_API_TOKEN>(仅 /health 免鉴权) |
| Token 位置 | crawl4ai-demo/.llm.env 的 CRAWL4AI_API_TOKEN |
| LLM | LLM_PROVIDER=deepseek/deepseek-chat,key 在 .llm.env |
| 容器限制 | 内存 4G、PID 512、shm_size 1g、只读根文件系统、非 root |
| 管理命令 | docker compose up -d / down / logs -f(在 crawl4ai-demo 目录执行) |
三条硬约束(违反必然出错):
- 没有
CRAWL4AI_API_TOKEN,服务只绑容器内回环地址,宿主端口映射返回Empty reply,而docker ps仍显示 healthy。token 是必需项。 shm_size必须 ≥ 1G,否则 Chromium 标签页频繁崩溃。- LLM 走白名单:
LLM_PROVIDER决定的 provider 家族之外一律拒绝(LLM provider not allowed)。
1. 三种使用形态
| 形态 | 谁跑浏览器 | 适用 |
|---|---|---|
| Python 库 | 你的进程 | 本地脚本、批量任务、要精细控制 |
| Docker 服务(本机) | 容器 | 多语言调用、服务化、不想装浏览器 |
| Crawl4AI Cloud | 官方 | 不想运维、要 web search(/search、/serp) |
本机是第二种。库和服务的配置对象完全一致,区别只是:库用 Python 对象传参,服务用 JSON 传参(见第 8 节的 type/params 约定)。
2. 两个核心配置对象
一次抓取只需记住两件事:用什么浏览器(BrowserConfig,一个实例复用)和这次怎么抓(CrawlerRunConfig,每次可不同)。
2.1 BrowserConfig 常用项【文档+实测】
| 参数 | 默认 | 说明 |
|---|---|---|
browser_type |
"chromium" |
可选 firefox / webkit |
headless |
True |
调试时设 False 看窗口 |
viewport_width/height |
1080/600 | 影响响应式布局,抓移动版页面要改 |
user_agent / user_agent_mode |
Linux Chrome UA / "" |
mode="random" 随机 UA 对抗检测 |
enable_stealth |
False |
playwright-stealth 改指纹 |
text_mode |
False |
禁图加速,纯文本抓取 |
light_mode |
False |
关后台功能提速 |
avoid_ads / avoid_css |
False |
拦广告域名 / 不加载 CSS |
proxy_config |
None |
代理(server/username/password) |
use_persistent_context + user_data_dir |
False |
持久化 profile,保留登录态 |
cookies / headers |
None |
直接注入 |
2.2 CrawlerRunConfig 常用项【文档+实测】
| 参数 | 默认 | 说明 |
|---|---|---|
word_count_threshold |
200 | 文本块最小词数,短文本站要调低 |
css_selector |
None |
全局作用域,所有提取都限定在此元素内 |
target_elements |
None |
只让 Markdown/结构提取聚焦若干元素,链接/图片仍取整页 |
excluded_tags |
None |
整体移除标签,如 ["nav","footer","form"] |
exclude_external_links / exclude_domains / exclude_social_media_links |
False/None |
链接过滤 |
exclude_external_images |
False |
去掉站外图片 |
cache_mode |
CacheMode.BYPASS |
见第 6 节 |
wait_for |
None |
"css:选择器" 或 "js:() => bool" |
js_code / js_code_before_wait |
None |
见第 5 节执行顺序 |
js_only |
False |
配合 session_id,不重新导航,只在当前页执行 JS |
session_id |
None |
复用同一个页面/会话 |
scan_full_page + scroll_delay |
False / 0.2 |
滚动触发懒加载 |
delay_before_return_html |
0.1 | 抓取前额外等待(秒) |
wait_until / page_timeout |
domcontentloaded / 60000 |
导航条件 / 超时(ms) |
screenshot / pdf / capture_mhtml |
False |
产出附加物 |
process_iframes |
False |
合并 iframe 内容 |
remove_overlay_elements / remove_consent_popups |
False |
去弹窗 / 去 GDPR 同意框 |
flatten_shadow_dom |
False |
展开 Shadow DOM(Web Component 站必开) |
virtual_scroll_config |
None |
虚拟滚动(内容被替换而非追加,如信息流) |
markdown_generator |
默认生成器 | 见第 3 节 |
extraction_strategy |
None |
见第 7 节 |
max_retries |
0 | 反爬失败重试轮数 |
选型口诀:要"只保留这块区域的全部内容"用 css_selector;要"正文聚焦但保留整页链接"用 target_elements。
3. Markdown 生成(这是 Crawl4AI 的主菜)
3.1 一次抓取产出四份 Markdown
result.markdown 是个对象,不是字符串:
| 字段 | 内容 | 用途 |
|---|---|---|
raw_markdown |
HTML→MD,未过滤 | 喂 LLM、存档原文 |
markdown_with_citations |
链接转脚注引用 | 需要标注来源 |
references_markdown |
单独的引用区块 | 溯源 |
fit_markdown |
过滤器裁剪后 | RAG/向量库省 token |
fit_html |
生成 fit 用的 HTML 片段 | 调试过滤效果 |
3.2 三种内容过滤器
| 过滤器 | 依据 | 需要查询词 | 场景 |
|---|---|---|---|
PruningContentFilterLXML |
文本密度/链接密度/结构 | 否 | 通用去噪,首选 |
BM25ContentFilter |
关键词相关性排序 | 是(必给 user_query) |
按主题聚焦 |
LLMContentFilter |
语义理解 | 用 instruction |
要高质量重组 |
旧
PruningContentFilter已弃用,换PruningContentFilterLXML(lxml 实现,大页面快约 10 倍)。
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator
from crawl4ai.content_filter_strategy import PruningContentFilterLXML
md_gen = DefaultMarkdownGenerator(
content_filter=PruningContentFilterLXML(threshold=0.5, threshold_type="fixed", min_word_threshold=50),
options={"ignore_links": True, "body_width": 0},
)
config = CrawlerRunConfig(markdown_generator=md_gen)
options 常用:ignore_links、ignore_images、escape_html、body_width(0=不换行)、skip_internal_links、include_sup_sub。
3.3 HTML 来源三选一(content_source)
"cleaned_html"(默认,清洗后)|"raw_html"(原始,清洗误删了内容时用)|"fit_html"(为 schema 抽取预处理)。
3.4 实测对比【实测】
同一页面 http://www.yingbofc.com/saishi.html,REST /md 的 f 参数:
| f | 输出长度 | 结论 |
|---|---|---|
fit(默认) |
436 字 | 剪枝过狠,正文被砍 |
raw |
2687 字 | 完整,中文站默认用这个 |
bm25 |
需 q,本次 1 字 |
无查询词时几乎抽空 |
llm |
686 字 | 把 div 布局还原成了 Markdown 表格 |
重要风险:
f=llm会"顺手修正"数据 — 源页面写2024-07-013(多一个 0),模型输出成2024-07-13且不作说明。入库时必须 raw + LLM 双存。
4. 内容选择与清洗
config = CrawlerRunConfig(
css_selector="main.content", # 硬限定作用域
# target_elements=["article", ".sidebar"], # 或软聚焦,保留整页链接
word_count_threshold=10,
excluded_tags=["nav", "footer", "form"],
exclude_external_links=True,
exclude_social_media_links=True,
exclude_domains=["ads.example.com"],
exclude_external_images=True,
)
| 需求 | 参数 |
|---|---|
| 只保留某块区域的全部提取 | css_selector |
| Markdown 聚焦多个元素、但保留整页链接/媒体 | target_elements |
| 整块删标签 | excluded_tags |
| 过滤外链/社交/域名/外图 | exclude_* 系列 |
文档中没有
excluded_selector这个参数,别去找。
iframe / 弹窗 / Shadow DOM:process_iframes=True、remove_overlay_elements=True、remove_consent_popups=True、flatten_shadow_dom=True(配 wait_until="load" + delay_before_return_html=2~5)。
5. 页面交互(动态站必看)
5.1 执行顺序(记这张图就不会乱)
1. page.goto(导航)
2. js_code_before_wait ← 先点 tab / 触发加载
3. wait_for ← 等元素或条件成立
4. delay_before_return_html ← 额外保险
5. js_code ← 在已加载完的页面上跑
6. flatten_shadow_dom
7. page.content() ← 抓 HTML
5.2 等待条件
config = CrawlerRunConfig(wait_for="css:.athing:nth-child(30)") # 等元素
config = CrawlerRunConfig(wait_for="js:() => document.querySelectorAll('.item').length > 50")
5.3 多步操作("加载更多")
config = CrawlerRunConfig(
js_code=["window.scrollTo(0, document.body.scrollHeight);",
"document.querySelector('a.morelink')?.click();"],
wait_for="js:() => document.querySelectorAll('.athing').length > 30",
js_only=True, # 不重新导航
session_id="hn_session", # 复用同一个页面
cache_mode=CacheMode.BYPASS,
)
session_id + js_only=True 是分页/无限滚动的标准组合;用完可 await crawler.crawler_strategy.kill_session(session_id)。
5.4 虚拟滚动(信息流类)
from crawl4ai import VirtualScrollConfig
VirtualScrollConfig(container_selector="[data-testid='primaryColumn']",
scroll_count=30, scroll_by="container_height", wait_after_scroll=1.0)
区别:普通滚动只留最终态;虚拟滚动会合并所有出现过的内容。
5.5 反检测相关
simulate_user、override_navigator、magic、enable_stealth、user_agent_mode="random"。
6. 缓存 CacheMode
| 值 | 语义 | 场景 |
|---|---|---|
ENABLED |
读写缓存(默认值在文档示例中为 BYPASS,注意版本差异) | 重复抓同一页、调试选择器 |
BYPASS |
本次跳过缓存 | 要最新数据 |
DISABLED |
完全不缓存 | 不留痕 |
READ_ONLY |
只读 | 离线回放 |
WRITE_ONLY |
只写 | 先灌缓存 |
旧参数(bypass_cache / disable_cache / no_cache_read / no_cache_write)在 0.5+ 已移除,只有 cache_mode。
7. 结构化抽取
7.1 无 LLM:CSS / XPath(快、免费、优先用)
from crawl4ai import JsonCssExtractionStrategy
schema = {
"name": "Articles",
"baseSelector": "div.article",
"fields": [
{"name": "title", "selector": "h2", "type": "text"},
{"name": "link", "selector": "a", "type": "attribute", "attribute": "href"},
{"name": "meta", "type": "nested", "fields": [
{"name": "author", "selector": ".author", "type": "text"},
{"name": "date", "selector": ".date", "type": "text"},
]},
],
}
config = CrawlerRunConfig(extraction_strategy=JsonCssExtractionStrategy(schema))
# result.extracted_content 是 JSON 字符串
7.2 有 LLM:语义抽取
from crawl4ai import LLMExtractionStrategy, LLMConfig
strategy = LLMExtractionStrategy(
llm_config=LLMConfig(provider="deepseek/deepseek-chat", api_token="env:DEEPSEEK_API_KEY"),
schema=MyModel.model_json_schema(), # 或手写 JSON Schema
extraction_type="schema", # schema | block
instruction="抽取产品名称与价格",
chunk_token_threshold=1000, # 分块上限,便于并行
overlap_rate=0.0,
apply_chunking=True,
input_format="markdown", # markdown | html | fit_markdown
extra_args={"temperature": 0.0, "max_tokens": 800},
)
strategy.show_usage() # 打印 token 用量
input_format 会影响准确率:指令依赖标签结构就用 html;纯文本抽取用 markdown;已过滤噪声用 fit_markdown(最省 token)。
8. REST API
8.1 端点全表【实测】
核心
| 端点 | 方法 | 说明 |
|---|---|---|
/health |
GET | 唯一免鉴权 |
/crawl |
POST | 同步抓取 |
/crawl/job |
POST | 异步任务,返回 task_id |
/crawl/job/{id} |
GET | 任务状态 |
/crawl/stream |
POST | 流式 |
/llm/job |
POST | LLM 抽取任务 |
/llm/job/{id} |
GET | 任务状态 |
/llm/{url} |
GET | 单页直出抽取 |
轻量专项
| 端点 | 说明 |
|---|---|
/md |
只要 Markdown,f=fit|raw|bm25|llm |
/html |
只要 HTML |
/screenshot |
截图,返回 base64 + artifact_id |
/pdf |
导出 PDF |
/execute_js |
执行 JS |
/artifacts/{id} |
下载产物(需 Bearer) |
运维
| 端点 | 说明 |
|---|---|
/metrics |
Prometheus 指标 |
/monitor/health、/monitor/browsers、/monitor/endpoints/stats |
运行状态 |
/monitor/logs/errors、/monitor/logs/janitor |
日志 |
/monitor/actions/cleanup、kill_browser、restart_browser |
手动干预 |
/hooks/info、/schema、/mcp/schema |
元信息 |
/playground |
交互界面 |
/config/dump、/token、/ask |
配置与辅助 |
8.2 配置对象必须 type/params 包装【实测】
这是 REST 与 Python 最大的差异,文档明确但很容易漏:
{
"urls": ["http://www.yingbofc.com/saishi.html"],
"crawler_config": {
"type": "CrawlerRunConfig",
"params": {
"cache_mode": "bypass",
"word_count_threshold": 5,
"css_selector": "body"
}
}
}
实测返回 200,raw_markdown 2690 字。字典类参数还要再套一层:{"type":"dict","value":{...}}。
browser_config 同理:{"type":"BrowserConfig","params":{"headless":true}}。
8.3 最小调用
TOKEN=$(grep '^CRAWL4AI_API_TOKEN=' .llm.env | cut -d= -f2)
# 只要 Markdown
curl -X POST localhost:11235/md -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"url":"https://example.com","f":"raw"}'
# 完整抓取
curl -X POST localhost:11235/crawl -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"urls":["https://example.com"]}'
8.4 异步 + Webhook
POST /crawl/job
{
"urls": ["https://example.com"],
"cache_mode": "bypass",
"webhook_config": {
"webhook_url": "https://your-app.com/hook",
"webhook_data_in_payload": true,
"webhook_headers": {"X-Webhook-Secret": "xxx"}
}
}
Webhook 重试:指数退避 5 次(0/1/2/4/8 秒),2xx 视为成功。
8.5 LLM 抽取
POST /llm/job
{
"url": "https://example.com/article",
"q": "提取标题、作者、日期、要点",
"provider": "deepseek/deepseek-chat",
"schema": "{\"title\":\"string\",\"author\":\"string\",\"points\":[\"string\"]}",
"cache": false
}
schema 必须是 JSON 字符串,传对象会 422。轮询 /llm/job/{task_id},status=completed 后取 llm_result。
9. 深度爬取(默认关闭)
本机已开(CRAWL4AI_ALLOW_DEEP_CRAWL=true)。REST 用法:
{
"urls": ["http://www.yingbofc.com/"],
"crawler_config": {"type":"CrawlerRunConfig","params":{
"deep_crawl_strategy": {"type":"BFSDeepCrawlStrategy","params":{
"max_depth": 1,
"max_pages": 2,
"filter_chain": {"type":"FilterChain","params":{"filters":[
{"type":"URLPatternFilter","params":{"patterns":["*/news/*"]}},
{"type":"DomainFilter","params":{"allowed_domains":["www.yingbofc.com"]}}
]}}
}}
}}
}
【实测】返回 2 条结果。策略可选 BFS / DFS / BestFirst(带打分)。约束:单一起始 URL、有大小与正则校验、拒绝 resume_state。
10. MCP 接入
# 本机实例(SSE)
claude mcp add --transport sse c4ai http://localhost:11235/mcp/sse
工具集:md、html、screenshot、pdf、execute_js、crawl、ask。
其他端点:/mcp/sse、/mcp/ws、/mcp/schema。
11. Python 客户端(连 Docker 服务)
import asyncio
from crawl4ai.docker_client import Crawl4aiDockerClient
async def main():
async with Crawl4aiDockerClient(base_url="http://localhost:11235", timeout=180) as c:
await c.authenticate("<CRAWL4AI_API_TOKEN>") # 形参名叫 email,实际传 token
r = await c.crawl(urls=["https://example.com"])
print(r.markdown.raw_markdown[:300])
asyncio.run(main())
- 方法只有
crawl/authenticate/get_schema/close timeout默认 30 秒,抓大站必调大- 另有
crawl4ai库模式(进程内跑浏览器)与crwlCLI(仅容器内可用)
12. 踩坑清单(全部本机验证过)
| 现象 | 原因 | 解法 |
|---|---|---|
Empty reply from server,但容器 healthy |
无 token → 只绑容器内 127.0.0.1 | 设 CRAWL4AI_API_TOKEN |
| 401 | token 缺失/错误;/health 免鉴权别用来判断 |
带 Bearer 头 |
422 schema: Input should be a valid string |
schema 传了对象 | 传 JSON 字符串 |
LLM provider not allowed |
provider 不在白名单 | 改 LLM_PROVIDER 并重建 |
| markdown 极短/为空 | f=fit 剪枝过度,或 bm25 没给 q |
用 f=raw |
| 抓取超时 | 客户端默认 30s / 页面需等待 | 调大 timeout、加 wait_for |
| 页面内容缺失 | 懒加载 / iframe / Shadow DOM | scan_full_page、process_iframes、flatten_shadow_dom |
| 分页只抓到第一页 | 没用 session | session_id + js_only=True |
| 中文站表格抽不出来 | div 布局,非 <table> |
f=llm 或 LLMExtractionStrategy |
13. 一页速查
要 Markdown → POST /md {"url":..., "f":"raw"}
要全字段 → POST /crawl {"urls":[...]}
要 JSON → /crawl + crawler_config.extraction_strategy(CSS 优先)
要语义抽取 → POST /llm/job {"url","q","schema":"<JSON字符串>"}
要截图/PDF → POST /screenshot | /pdf → /artifacts/{id}
要清噪 → PruningContentFilterLXML(threshold=0.5)
要限定区域 → css_selector(硬) / target_elements(软)
要翻页 → session_id + js_only + js_code
要登录态 → BrowserConfig.use_persistent_context / cookies / session_id
要提速 → cache_mode=ENABLED、text_mode、light_mode、avoid_ads
常见问题
Crawl4AI 怎么安装?
最省事是 Docker:unclecode/crawl4ai 镜像,0.9.5 实测可用。必须设 CRAWL4AI_API_TOKEN——不设的时候服务只绑容器内回环地址,宿主端口映射返回 Empty reply from server,而 docker ps 还显示 healthy。shm_size 也要 ≥1G,否则 Chromium 标签页频繁崩。
抓取结果怎么转成 Markdown?
直接 POST /md {"url":..., "f":"raw"},要全字段就 POST /crawl。f=fit 会剪枝,短页面容易剪成空;f=bm25 必须给 q,否则内容极短。所以调试期统一先用 raw,确认抓到了再上过滤器。
需要浏览器依赖吗?无头模式怎么配?
用 Docker 镜像就不用自己装 Chromium。库模式才需要本地浏览器,配置走 BrowserConfig(headless=True)。动态站还要配 wait_for、scan_full_page、process_iframes;分页必须用 session_id 加 js_only=True,否则永远只抓到第一页。
怎么避免被反爬?
先降特征再谈代理:text_mode / light_mode 提速、cache_mode=ENABLED 减少重复请求、按站点加退避。真要过强防护时,浏览器指纹和 IP 池才是瓶颈,而这一步已经进入合规边界——Crawl4AI 提升的是采集能力,不等于可以绕过访问控制。
延伸阅读:Crawl4AI 值不值得商业化、八个阶段的研究路线、把采集接进 Agent:Crawl4AI + Hermes
Comments (0)
Say something… (max 250 characters)