首页
/ Crawl4AI CLI 实战指南:从 crwl 一条命令到配置、抽取、过滤、问答与深度爬取

Crawl4AI CLI 实战指南:从 crwl 一条命令到配置、抽取、过滤、问答与深度爬取

2026-09-06 15:02:26作者:傅爽业Veleda

本文围绕 Crawl4AI 官方 CLI 文档(docs/md_v2/core/cli.md)展开,系统讲解命令行工具 crwl 的安装方式、基础爬取、浏览器/爬虫/抽取三类配置的 YAML 与参数双模式用法、CSS 与 LLM 结构化抽取、BM25 与剪枝内容过滤、基于 LLM 的交互式问答(Q&A)、输出格式以及深度爬取等完整能力。并结合 CLI 源码实现全局配置定义示例配置文件,帮助你在终端中快速完成“爬取—过滤—抽取—问答”的完整数据管道,并理解每个参数在源码中的真实作用。

安装与入口:crwl 从哪来

CLI 随库一起安装,无需单独安装。从 pyproject.toml 的入口声明可以看到,crwl 是一个标准的 Python 包入口点,指向 crawl4ai.cli:main

[project.scripts]
crawl4ai-download-models = "crawl4ai.model_loader:main"
crawl4ai-migrate = "crawl4ai.migrations:main"
crawl4ai-setup = "crawl4ai.install:post_install"
crawl4ai-doctor = "crawl4ai.install:doctor"
crwl = "crawl4ai.cli:main"

因此执行 pip install crawl4ai 后即可直接使用 crwl(要求 Python >= 3.10,见 pyproject.toml)。

从源码结构看,crwl 背后是一个 click 命令组,包含多组子命令:

  • 默认命令(名为空串)crwl https://example.com 实际等价于 crwl crawl https://example.com。在 main() 函数 中,当第一个参数不是已注册的子命令时会自动插入 crawl,实现“裸 URL 直接爬取”的体验;
  • crwl crawl:带完整选项的爬取命令;
  • crwl profiles:浏览器配置文件(身份/登录态)管理;
  • crwl browser:内置浏览器实例管理(start / stop / status / view / restart);
  • crwl cdp:启动带 CDP 调试端口的独立浏览器,供 Puppeteer、Playwright 等外部工具接入;
  • crwl config:查看与修改全局配置;
  • crwl examples:打印示例集合(即 crwl --example 的内容)。

基础用法

最简形态如下:

# Basic crawling
crwl https://example.com

# Get markdown output
crwl https://example.com -o markdown

# Verbose JSON output with cache bypass
crwl https://example.com -o json -v --bypass-cache

# See usage examples
crwl --example

几个值得注意的行为细节(来自 crawl_cmd 定义):

  • 默认输出是 all,即把完整的 CrawlResult 序列化为 JSON 打印,包含 metadata、markdown、links 等全部字段;
  • --bypass-cache 在 CLI 中默认开启default=True),即 CLI 场景下默认绕过缓存直接重新爬取,这与库代码中 CrawlerRunConfig 的默认缓存行为不同,是从源码结构看的一个值得留意的差异;
  • -v(verbose)会在爬取前打印完整的浏览器与爬虫配置(browser_cfg.dump() / crawler_cfg.dump()),便于排查参数是否生效,见 run_crawler

官方文档给出的进阶快速示例:克隆仓库后运行下面命令,即可按仓库中的 JSON-CSS schema 获得 InfoQ 页面的 JSON 内容:

crwl "https://www.infoq.com/ai-ml-data-eng/" -e docs/examples/cli/extract_css.yml -s docs/examples/cli/css_schema.json -o json;

配置体系:文件、参数与全局设置三层

Crawl4AI CLI 的配置分三层:YAML/JSON 配置文件(-B/-C/-e/-f)、命令行键值参数(-b/-c)、全局用户配置(~/.crawl4ai/global.yml)。文件与参数可以叠加,参数覆盖文件

浏览器配置(Browser Configuration)

浏览器设置可通过 YAML 文件或命令行参数配置:

# browser.yml
headless: true
viewport_width: 1280
user_agent_mode: "random"
verbose: true
ignore_https_errors: true
# Using config file
crwl https://example.com -B browser.yml

# Using direct parameters
crwl https://example.com -b "headless=true,viewport_width=1280,user_agent_mode=random"

仓库中完整的浏览器配置示例见 docs/examples/cli/browser.yml,包含更多常用字段:

browser_type: "chromium"
headless: true
viewport_width: 1280
viewport_height: 800
user_agent_mode: "random"
verbose: true
text_mode: false
light_mode: false
ignore_https_errors: true
java_script_enabled: true
extra_args:
  - "--disable-gpu"
  - "--no-sandbox"

其中 browser_type 支持 chromium / firefoxuser_agent_mode 支持 default / random / mobileextra_args 用于透传 Chromium 启动参数。

爬虫配置(Crawler Configuration)

控制爬取行为:

# crawler.yml
cache_mode: "bypass"
wait_until: "networkidle"
page_timeout: 30000
delay_before_return_html: 0.5
word_count_threshold: 100
scan_full_page: true
scroll_delay: 0.3
process_iframes: false
remove_overlay_elements: true
magic: true
verbose: true
# Using config file
crwl https://example.com -C crawler.yml

# Using direct parameters
crwl https://example.com -c "css_selector=#main,delay_before_return_html=2,scan_full_page=true"

仓库示例 docs/examples/cli/crawler.yml 还额外启用了 exclude_external_links: trueexclude_social_media_links: true(用于过滤外链与社交链接,主要影响深度爬取时的链接发现)。各字段的作用:

字段 作用
cache_mode 缓存模式:bypass / use / refresh
wait_until 页面加载等待条件,如 networkidle
page_timeout 单页超时(毫秒)
delay_before_return_html 返回 HTML 前的等待秒数,适配动态内容
word_count_threshold 生成 fit markdown 时的最低词数阈值
scan_full_page 是否整页滚动(无限滚动页面需要)
scroll_delay 整页滚动时每步延迟(秒)
process_iframes 是否处理 iframe 内容
remove_overlay_elements 移除弹窗/遮罩等覆盖层元素
magic 启用 magic 优化(自动处理滚动、懒加载等)

命令行参数的类型解析

-b-c 接受的 key1=value1,key2=value2 字符串由 parse_key_values 解析,内置类型推断:

  • true / false → 布尔值;
  • 纯数字 → int,含小数点 → float(如 delay_before_return_html=0.5);
  • [a,b,c] → 列表;
  • {...} → JSON 对象(解析失败会抛出 BadParameter)。

所以 -c "css_selector=#main,delay_before_return_html=2,scan_full_page=true" 会被解析为带正确类型的字典,再通过 browser_cfg.clone(**browser) / crawler_cfg.clone(**crawler) 覆盖到从 YAML 加载的默认配置上(见 配置合并逻辑)。

全局配置:~/.crawl4ai/global.yml 与 crwl config

LLM 凭据、浏览器默认行为等会持久化在 ~/.crawl4ai/global.yml,其可设置项定义在 config.py 的 USER_SETTINGS

设置项 默认值 说明
DEFAULT_LLM_PROVIDER openai/gpt-4o 默认 LLM 提供方,格式 company/model
DEFAULT_LLM_PROVIDER_TOKEN 默认 LLM 的 API token(列表时脱敏显示)
VERBOSE false 全局 verbose 输出
BROWSER_HEADLESS true 浏览器默认是否 headless
BROWSER_TYPE chromium 默认浏览器类型(chromium / firefox)
CACHE_MODE bypass 默认缓存模式(bypass / use / refresh)
USER_AGENT_MODE default 默认 UA 模式(default / random / mobile)
JSON_ENSURE_ASCII true JSON 输出是否转义非 ASCII 字符

对应三组子命令:

crwl config list                                    # 以表格列出全部设置、当前值与默认值
crwl config get DEFAULT_LLM_PROVIDER                # 查看单个设置
crwl config set DEFAULT_LLM_PROVIDER "anthropic/claude-3-sonnet"
crwl config set DEFAULT_LLM_PROVIDER_TOKEN "your-api-token-here"
crwl config set BROWSER_HEADLESS false              # 默认显示浏览器窗口
crwl config set USER_AGENT_MODE random             # 使用随机 UA

set 会做类型校验:布尔值只接受 true/false/yes/no/1/0,带 options 的设置(如 BROWSER_TYPE)只接受枚举内的取值;密钥类设置回显为 ********(见 config_set_cmd)。

结构化数据抽取

CLI 支持两种抽取路径:配置文件驱动的抽取-e + -s)和快速 LLM 抽取-j)。

配置文件驱动:json-css / json-xpath / llm

-e 指定抽取策略配置文件(YAML/JSON),-s 指定 schema 文件。源码中校验 type 必须是 llmjson-cssjson-xpath 之一(见 抽取策略分发)。

1. 基于 CSS 选择器的抽取(json-css)

# extract_css.yml
type: "json-css"
params:
  verbose: true
// css_schema.json
{
  "name": "ArticleExtractor",
  "baseSelector": ".article",
  "fields": [
    {
      "name": "title",
      "selector": "h1.title",
      "type": "text"
    },
    {
      "name": "link",
      "selector": "a.read-more",
      "type": "attribute",
      "attribute": "href"
    }
  ]
}

仓库中可直接运行的实例见 docs/examples/cli/extract_css.ymldocs/examples/cli/css_schema.json(后者用 baseSelector: ".cards[data-tax=news] .card__data" 抽取列表页的 title / link / details / topics 四个字段,正好对应上面文档快速示例)。

2. 基于 LLM 的抽取(llm)

# extract_llm.yml
type: "llm"
provider: "openai/gpt-4"
instruction: "Extract all articles with their titles and links"
api_token: "your-token"
params:
  temperature: 0.3
  max_tokens: 1000
// llm_schema.json
{
  "title": "Article",
  "type": "object",
  "properties": {
    "title": {
      "type": "string",
      "description": "The title of the article"
    },
    "link": {
      "type": "string",
      "description": "URL to the full article"
    }
  }
}

params 内的键会作为 **kwargs 透传给 LLMExtractionStrategy,因此 temperaturemax_tokenschunk_token_thresholdoverlap_rateword_token_rateverbose 等参数均可配置。LLM 抽取时缺少 providerapi_token 会直接报错“LLM provider and API token are required for LLM extraction”(见 CLI 校验逻辑)。

一个实用细节:api_token 支持 env:变量名 前缀,从源码看 LLMConfig 初始化 会将其解析为 os.getenv(api_token[4:])。因此推荐把 token 留在环境变量里而不是写死在配置文件中,仓库示例 docs/examples/cli/extract.yml 正是这种写法:

type: "llm"
provider: "openai/gpt-4o-mini"
api_token: "env:OPENAI_API_KEY"
instruction: "Extract all articles with their titles, authors, publication dates and main topics in a structured format"
params:
  chunk_token_threshold: 4096
  overlap_rate: 0.1
  word_token_rate: 0.75
  temperature: 0.3
  max_tokens: 1000
  verbose: true

抽取命令:

# CSS 选择器抽取
crwl https://example.com \
    -e extract_css.yml \
    -s css_schema.json \
    -o json

# LLM 抽取
crwl https://example.com \
    -e extract_llm.yml \
    -s llm_schema.json \
    -o json

快速 LLM 抽取:-j

-j--json-extract)跳过配置文件,直接用 LLM 抽取结构化数据,优先级高于 -e。可以不带参数,也可以带一段自然语言指令:

# 自动推断结构化数据
crwl https://example.com -j

# 带具体指令
crwl https://example.com -j "Extract product details including name, price, and features"

# 实际案例:抽取亚马逊商品字段
crwl https://amazon.com/dp/B01DFKC2SO \
    -j "Extract product title, current price, original price, rating, and all product specifications" \
    -b "headless=true,viewport_width=1280" \
    -v

源码实现 看,-j 内部构造的 LLMExtractionStrategy 固定使用 extraction_type="schema"apply_chunking=Falseforce_json_response=True;不带指令时使用一段内置的通用指令(识别列表型/文章型页面并返回合法 JSON)。若未显式指定 -o,输出会自动切到 json。首次使用会提示输入 provider 与 token 并保存到 ~/.crawl4ai/global.yml(流程见 setup_llm_config)。

内容过滤:bm25 与 pruning

通过 -f 指定过滤配置,输出 markdown-fit 可获得聚焦后的精简 Markdown。支持两种类型(源码见 过滤器装配):

# filter_bm25.yml
type: "bm25"
query: "target content"
threshold: 1.0

# filter_pruning.yml
type: "pruning"
query: "focus topic"
threshold: 0.48
crwl https://example.com -f filter_bm25.yml -o markdown-fit
  • bm25:构造 BM25ContentFilter,参数有 query(相关性查询)、threshold(BM25 分数阈值,默认 1.0)、use_stemming(默认 true,启用词干化);
  • pruning:构造 PruningContentFilter,参数有 querythreshold(默认 0.48);
  • 未提供 -f 但输出为 markdown-fit,CLI 会自动使用 pruning 过滤,threshold=0.48(见 默认过滤兜底),即 -o markdown-fit 单独使用也可得到过滤后的结果。

过滤器最终挂载到 DefaultMarkdownGenerator.content_filter,因此影响的是 fit_markdown 输出,raw_markdown-o markdown)不受影响。

LLM 问答(-q)

爬取完成后可以直接对页面内容提问:

# 简单提问
crwl https://example.com -q "What is the main topic discussed?"

# 先看内容再提问
crwl https://example.com -o markdown  # See content first
crwl https://example.com -q "Summarize the key points"
crwl https://example.com -q "What are the conclusions?"

# 结合高级爬取参数
crwl https://example.com \
    -B browser.yml \
    -c "css_selector=article,scan_full_page=true" \
    -q "What are the pros and cons mentioned?"

首次使用须知(与 setup_llm_config 源码一致):

  • 首次会交互式提示 LLM provider(company/model 格式)与 API token,并保存到 ~/.crawl4ai/global.yml
  • provider 以 ollama/ 开头时无需提供 token(源码中会写入占位值 no-token);
  • 完整 provider 列表以 LiteLLM 官方文档为准(CLI 示例输出中也给出 ollama/llama3.3openai/gpt-4anthropic/claude-3-sonnetcohere/commandgoogle/gemini-pro 等常见示例);
  • 也可以提前用 crwl config set DEFAULT_LLM_PROVIDER ...crwl config set DEFAULT_LLM_PROVIDER_TOKEN ... 配置,避免每次交互。

从实现看,stream_llm_response 通过 litellm 的 completion(..., stream=True) 流式输出答案,系统提示词明确告知模型“基于从该 URL 爬取的内容回答”,用户消息以 <|start of context|> / <|end of context|> 包裹爬取的 Markdown 正文。注意 -q 模式下爬取的是第一个(主)结果的内容,输出答案为纯文本流而非 JSON。

输出格式与落盘

-o--output)支持以下取值(见 选项定义):

取值 说明
all(默认) 完整 CrawlResult 的 JSON 序列化,包含元数据
json 仅输出抽取的结构化数据(配合抽取策略使用时)
markdown / md 原始 Markdown(raw_markdown
markdown-fit / md-fit 经内容过滤/精简的 Markdown(fit_markdown

补充两个源码中提供、便于工程化使用的选项:

  • -O <file>--output-file):结果写入文件而非 stdout,写入逻辑与 stdout 各格式一一对应(见 输出落盘分支);
  • --json-ensure-ascii / --no-json-ensure-ascii:控制 JSON 中非 ASCII 字符是否转义(如 š\u0161),优先级为“CLI 参数 > 全局配置 JSON_ENSURE_ASCII > 默认 true”。

深度爬取(--deep-crawl)

crawl 命令支持通过 --deep-crawl 启用深度爬取,策略可选 bfsdfsbest-first--max-pages 控制最大页面数(默认 10):

crwl https://example.com --deep-crawl bfs --max-pages 20 -o markdown

深度爬取装配逻辑 看,CLI 分别构造 BFSDeepCrawlStrategy / DFSDeepCrawlStrategy / BestFirstCrawlingStrategy,其中 max_depth 在 CLI 路径上固定为 3,max_pages--max-pages 的值。深度爬取返回的是结果列表:-o all 输出 JSON 数组,markdown/markdown-fit 会按页拼接并以 # {url} 分隔,-q 则基于第一个结果回答(见 结果分支处理)。

浏览器 Profile、内置浏览器与 CDP

CLI 还内置了三组浏览器管理能力,配合 crwl --example 可查看完整示例输出。

身份型爬取(Profile)-p <profile-name> 会按名称查找 profile 并注入到浏览器配置(设置 user_data_diruse_managed_browser=True),从而复用登录态(见 profile 注入逻辑):

# 交互式管理:列表 / 创建 / 删除 / 用 profile 爬取
crwl profiles

# 非交互式子命令
crwl profiles create github-auth
crwl profiles list
crwl profiles delete old-profile --force

# 用登录态 profile 爬取需要鉴权的页面
crwl https://site-requiring-login.com/dashboard -p github-auth -o markdown

# 瘦身 profile:保留 cookies/localStorage/IndexedDB 等认证数据
crwl shrink my_profile --level aggressive --dry-run

crwl shrink 支持 light(仅清缓存)、medium(缓存+历史)、aggressive(默认,仅保留认证数据)、minimal(仅 cookies + localStorage)四档,并可用 --dry-run 预览(见 shrink 命令),底层由 browser_profiler.py 中的 BrowserProfiler 实现。

内置浏览器管理

crwl browser start --browser-type chromium --port 9223 --no-headless
crwl browser status
crwl browser view --url https://example.com
crwl browser stop
crwl browser restart

browser start 会启动一个常驻浏览器实例并打印 CDP URL;代码中设置 browser_mode="builtin"(或 CLI 里 -b "browser_mode=builtin")即会复用该实例(见 browser_start_cmd)。

CDP 调试浏览器

crwl cdp                              # 默认端口 9222
crwl cdp -p my-profile -P 9223        # 指定 profile 与端口
crwl cdp --headless
crwl cdp --incognito                   # 忽略 user-data-dir
crwl cdp --user-data-dir ~/browser-data --port 9223

crwl cdp 启动带 Chrome DevTools Protocol 调试的独立浏览器并打印 CDP URL,浏览器持续运行直到在终端按 q(见 cdp_cmd),可被 Puppeteer、Playwright 等外部工具直接连接。

完整示例

以下四组完整示例继承自官方文档,覆盖典型使用场景:

# 1. 基础抽取:浏览器 + 爬虫双配置文件
crwl https://example.com \
    -B browser.yml \
    -C crawler.yml \
    -o json

# 2. 结构化数据抽取(CSS 选择器 + schema)
crwl https://example.com \
    -e extract_css.yml \
    -s css_schema.json \
    -o json \
    -v

# 3. LLM 抽取 + 内容过滤
crwl https://example.com \
    -B browser.yml \
    -e extract_llm.yml \
    -s llm_schema.json \
    -f filter_bm25.yml \
    -o json

# 4. 交互式问答:先看内容,再提问
crwl https://example.com -o markdown
crwl https://example.com -q "What are the main points?"
crwl https://example.com -q "Summarize the conclusions"

最佳实践

官方文档给出的实践建议,结合源码行为补充如下:

  1. 配置管理:常用配置沉淀到 YAML 文件(-B/-C/-e/-f),临时改动用 -b/-c 参数覆盖;API token 等敏感信息放 ~/.crawl4ai/global.ymlcrwl config set),LLM 配置文件中优先使用 env: 前缀引用环境变量;
  2. 性能优化:需要最新内容时使用 --bypass-cache(CLI 默认已开启);无限滚动页面开启 scan_full_page=true 并配合 scroll_delay;动态内容用 delay_before_return_htmlwait_until 控制时机;
  3. 内容抽取:结构稳定的页面用 CSS/XPath 抽取(确定性、零成本),结构不固定或需要语义理解的页面用 LLM 抽取(-e extract_llm.yml-j);配合 -f 过滤可获得聚焦结果;
  4. 问答工作流:先用 -o markdown 确认爬到的内容质量,再提问;必要时用 css_selectorscan_full_page 扩大或收窄上下文,提高回答质量。

CLI 的自动化测试可参考 tests/cli/test_cli.py

小结

Crawl4AI CLI(crwl)在一条命令内提供了完整的终端侧数据管道能力:

  • 灵活配置:YAML 文件、key=value 参数、~/.crawl4ai/global.yml 全局设置三层叠加,参数自动完成布尔/数值/列表/JSON 类型解析;
  • 多种抽取策略:CSS(json-css)、XPath(json-xpath)、LLM(llm 配置文件与 -j 快速模式),token 支持 env: 环境变量引用;
  • 内容过滤:BM25 与剪枝两种过滤器,markdown-fit 无配置时自动走 pruning 兜底;
  • 交互式问答-q 基于 LiteLLM 流式回答,首次配置自动持久化,ollama/ 本地模型免 token;
  • 浏览器能力:profile 身份爬取与瘦身、内置浏览器生命周期管理、CDP 调试端;
  • 深度爬取bfs / dfs / best-first 三策略,页面数可控,结果按页拼接输出;
  • 输出格式all / json / markdown / markdown-fit,支持 -O 落盘与 ASCII 转义控制。

所有行为均可在 crawl4ai/cli.py 中逐行核对,示例配置文件位于 docs/examples/cli/,可据此搭建可复制、可复现的命令行抓取管道。

登录后查看全文
热门项目推荐
相关项目推荐