GEO

如何用LLM自动提取网页结构化数据?Trawl工具实测解析

2026/4/10
如何用LLM自动提取网页结构化数据?Trawl工具实测解析

AI Summary (BLUF)

trawl is an LLM-powered web scraping tool that extracts structured data from websites using semantic queries instead of CSS selectors. It automatically adapts to site redesigns and runs efficiently in Go after initial strategy derivation.

原文翻译: trawl是一款基于LLM的网页爬取工具,通过语义查询而非CSS选择器从网站提取结构化数据。它能自动适应网站改版,并在初始策略推导后以Go语言高效运行。

trawl

Trawl 是一款利用大型语言模型(LLM)从任何网站提取结构化数据的工具。它允许您从语义层面定义想要什么,而不是使用 CSS 选择器,然后由工具自行推导如何提取。当网站改版时,Trawl 会自动重新推导提取策略。LLM 的调用频率是每个网站结构一次,而非每页一次。稳定状态下的数据抓取完全由 Go 语言驱动,速度极快,且无需支付任何 API 调用费用。

Trawl 是一款利用大型语言模型(LLM)从任何网站提取结构化数据的工具。它允许您从语义层面定义想要什么,而不是使用 CSS 选择器,然后由工具自行推导如何提取。当网站改版时,Trawl 会自动重新推导提取策略。LLM 的调用频率是每个网站结构一次,而非每页一次。稳定状态下的数据抓取完全由 Go 语言驱动,速度极快,且无需支付任何 API 调用费用。


安装

您可以通过多种方式安装 Trawl。

You can install Trawl in several ways.

使用安装脚本

curl -fsSL https://raw.githubusercontent.com/akdavidsson/trawl/main/install.sh | sh

使用 Go 安装

go install github.com/akdavidsson/trawl@latest

从源码构建

git clone https://github.com/akdavidsson/trawl
cd trawl
go build -o trawl .

快速开始

首先,设置您的 API 密钥。

First, set up your API keys.

export GOOGLE_GEMINI_APIKEY=AIzaSy...
# 或者,如果使用 Anthropic:
export ANTHROPIC_API_KEY=sk-ant-...

然后,您可以开始提取数据。

Then, you can start extracting data.

# 以 JSON 格式提取产品数据
trawl "https://books.toscrape.com" --fields "title, price, rating, in_stock"

# 以 CSV 格式输出
trawl "https://books.toscrape.com" --fields "title, price" --format csv

# 预览提取计划而不实际执行提取
trawl "https://books.toscrape.com" --fields "title, price" --plan

核心概念与工作原理

Trawl 的核心创新在于将 LLM 的语义理解能力与传统的高效 CSS 选择器提取相结合,实现了“一次学习,多次使用”的智能抓取模式。

The core innovation of Trawl lies in combining the semantic understanding capabilities of LLMs with traditional, efficient CSS selector extraction, achieving an intelligent scraping model of "learn once, use many times."

工作流程详解

Trawl 的工作流程是一个智能化的管道,旨在最大化效率并最小化 LLM 调用成本。

Trawl's workflow is an intelligent pipeline designed to maximize efficiency and minimize LLM call costs.

  1. 获取页面:获取目标 URL 的内容。使用 --js 标志时,会启动无头 Chromium 浏览器来渲染 JavaScript。浏览器会自动:
    • 等待 DOM 稳定:轮询页面直到元素数量不再变化,并且骨架屏加载占位符(如 .animate-pulse)被解析,确保 React/Next.js 等单页应用完成渲染。
    • 滚动页面:触发基于 Intersection Observer 的懒加载,确保页面下方的数据区域被渲染。
    • 点击“显示更多”按钮:展开隐藏的数据(最多进行 3 轮)。
    • 捕获 iframe 内容:对于像 HuggingFace Spaces 这样将应用嵌入 iframe 的网站,Trawl 会检查所有 iframe,比较内容丰富度,并选择最丰富的内容源。
  2. 检测数据区域:使用启发式分析查找候选数据区域,如表格、列表和重复的 div/section 模式。每个区域根据内容丰富度(平均项目大小)进行评分,以区分真实数据与导航栏、页脚和 SVG 图表。同时捕获区域标题和 HTML id 属性作为上下文。
  3. 检查缓存:如果存在针对此 URL 模式 + 结构指纹的提取策略,则完全跳过 LLM 调用。
  4. 推导策略:通过 LLM API 推导策略。发送来自顶级候选区域的、聚焦于单个项目的 HTML 片段(而非整个页面),连同区域上下文、查询文本和字段描述。LLM 返回 CSS 选择器、用于将提取范围限定在正确页面区域的 container_selector、属性映射、转换规则和备用选择器。如果选择器在页面验证失败,系统会自动尝试带有反馈的重试。
  5. 提取数据:使用纯 Go 语言和 goquery 库,在限定的容器范围内应用 CSS 选择器提取数据。大多数字段为空的记录(来自不匹配的区域)会被自动过滤掉。
  6. 监控健康度:跟踪已填充字段的百分比。如果该比例降至 70% 以下,则触发自我修复机制——重新推导策略,并保留效果更好的那个。
  7. 输出结果:将结果输出为 JSON、JSONL、CSV 或 Parquet 格式。
  1. Fetch: Retrieve the content of the target URL. When using the --js flag, a headless Chromium browser is launched to render JavaScript. The browser automatically:
    • Waits for DOM stability: Polls the page until element counts stop changing and skeleton loading placeholders (e.g., .animate-pulse) are resolved, ensuring SPAs like React/Next.js finish rendering.
    • Scrolls the page: Triggers intersection-observer-based lazy loading to ensure data sections further down the page are rendered.
    • Clicks "Show more" buttons: Expands hidden data (up to 3 rounds).
    • Captures iframe content: For sites like HuggingFace Spaces that embed their app inside an iframe, Trawl inspects all iframes, compares content richness, and uses the richest source.
  2. Detect Data Regions: Uses heuristic analysis to find candidate data regions such as tables, lists, and repeated div/section patterns. Each region is scored by content richness (average item size) to distinguish real data from navigation, footers, and SVG charts. Section headings and HTML id attributes are captured for context.
  3. Check Cache: If an extraction strategy exists for this URL pattern + structural fingerprint, the LLM call is skipped entirely.
  4. Derive Strategy: Derives the strategy via the LLM API. Sends focused single-item HTML snippets from the top candidate regions (not the full page), along with section context, query text, and field descriptions. The LLM returns CSS selectors, a container_selector to scope extraction to the correct page section, attribute mappings, transforms, and fallback selectors. If the selectors fail validation against the page, a retry with feedback is attempted automatically.
  5. Extract Data: Uses pure Go and the goquery library to apply CSS selectors within the scoped container for data extraction. Records where most fields are null (from mismatched sections) are automatically filtered out.
  6. Monitor Health: Tracks the percentage of fields that were populated. If it drops below 70%, self-healing is triggered—the strategy is re-derived, and the one that produces better results is kept.
  7. Output Results: Outputs the results in JSON, JSONL, CSV, or Parquet format.

关键优势:LLM 仅被调用一次来推导选择器。此后,所有具有相同结构的页面都使用缓存的策略进行提取——纯 Go 执行,无需 API 调用,没有 Token 成本。

Key Advantage: The LLM is called only once to derive the selectors. Every subsequent page with the same structure uses the cached strategy for extraction—pure Go execution, no API calls, no token cost.


使用指南与示例

Trawl 提供了灵活的命令行接口,支持从简单字段提取到复杂场景处理。

Trawl provides a flexible command-line interface, supporting everything from simple field extraction to complex scenario handling.

基本命令格式

trawl [url] [flags]

常用示例

场景 命令示例 说明
简单字段提取 trawl "https://example.com/products" --fields "name, price, rating, url" --format json 提取指定字段并以 JSON 格式输出。
使用 YAML 模式文件 trawl "https://example.com/products" --schema products.yaml --format csv 通过 YAML 文件精确定义提取模式和字段转换规则。
自然语言查询 trawl "https://example.com/products" --query "extract all product listings with names, prices, and stock status" Trawl 会根据数据推断字段名称,无需预先指定。
处理 JavaScript 渲染页面 trawl "https://example.com/spa" --fields "name, value" --js 启用无头浏览器以抓取 React、Vue 等框架生成的动态内容。
处理 iframe 嵌入应用 trawl "https://huggingface.co/spaces/..." --fields "rank, model, average" --js --wait 10s 针对 iframe 内容,增加等待时间确保应用完全加载。
使用自定义请求头 trawl "https://example.com/dashboard" --fields "metric, value" --headers "Authorization: Bearer token123" --cookie "session=abc123" 添加认证头或 Cookie 以访问需要登录的页面。
重用缓存策略 trawl "https://example.com/products" --strategy cached-strategy.json --format csv 直接使用之前保存的提取策略文件,完全跳过 LLM 调用。

命令行参数详解

Trawl 的参数按功能模块组织,便于理解和使用。

Trawl's flags are organized by functional modules for easy understanding and use.

输入参数

这些参数定义了要提取什么数据。

These flags define what data to extract.

参数 简写 默认值 描述
--fields -f - 要提取的字段名,以逗号分隔。
--query -q - 描述要提取内容的自然语言文本。
--schema -s - YAML 模式文件的路径,用于精确定义提取规则。

--query 参数特别有用,尤其适用于包含多个数据区域的页面。查询文本会与区域标题和 HTML ID 进行匹配,以优先选择正确的数据区域,并传递给 LLM 以帮助其选择最相关的部分。当与 --fields 一起使用时,查询指导区域选择,而字段定义输出结构。

The --query flag is especially useful for pages with multiple data sections. The query text is matched against section headings and HTML IDs to prioritize the right data region and is passed to the LLM so it can select the most relevant section. When used together with --fields, the query guides section selection while the fields define the output structure.

输出参数

控制提取结果的格式和目的地。

Control the format and destination of the extraction results.

参数 简写 默认值 描述
--format - json 输出格式:json, jsonl, csv, parquet
--output -o stdout 将输出写入文件而非标准输出。

爬取控制参数

管理如何抓取页面,包括并发、延迟和 JavaScript 处理。

Manage how pages are crawled, including concurrency, delays, and JavaScript handling.

参数 简写 默认值 描述
--max-pages -n 1 要抓取的最大页面数。
--paginate - - 自动检测并跟随分页链接。
--concurrency -c 10 并发工作线程数。
--delay - 1s 对同一域名的请求之间的延迟。
--js - - 为 JavaScript 渲染的页面启用无头浏览器。
--wait - 0 使用 --js 时,页面加载后额外等待的时间(例如 5s)。

策略管理参数

控制提取策略的生成、缓存和使用。

Control the generation, caching, and usage of extraction strategies.

参数 默认值 描述
--strategy - 缓存的提取策略 JSON 文件的路径。
--plan - 试运行:显示 LLM 推导出的提取计划,但不执行提取。
--no-cache - 不使用缓存,也不缓存新生成的策略。
--no-heal - 禁用自我修复功能(失败时不重新推导策略)。

LLM 配置参数

配置与大型语言模型相关的选项。

Configure options related to the Large Language Model.

参数 默认值 描述
--model - 要使用的 LLM 模型(默认取决于 API 密钥)。
--no-llm - 禁用 LLM,仅使用启发式提取方法。

总结

Trawl 代表了网页数据提取领域的一个创新方向。它巧妙地将 LLM 的语义理解能力用于解决传统抓取工具中最脆弱、最易失效的环节——选择器定位,而将大规模、高并发的数据提取任务交给高效、稳定的原生 Go 代码执行。这种“智能推导 + 高效执行”的架构,使得 Trawl 在应对现代动态网站、单页应用以及频繁改版的网站时,兼具了强大的适应性和卓越的性能表现,同时将 LLM 的使用成本控制在最低水平。

Trawl represents an innovative direction in the field of web data extraction. It cleverly uses the semantic understanding capabilities of LLMs to address the most fragile and failure-prone aspect of traditional scraping tools—selector localization—while delegating the large-scale, high-concurrency data extraction tasks to efficient and stable native Go code. This architecture of "intelligent derivation + efficient execution" enables Trawl to combine powerful adaptability with excellent performance when dealing with modern dynamic websites, single-page applications, and frequently updated sites, all while keeping the cost of LLM usage to a minimum.

常见问题(FAQ)

Trawl 如何自动适应网站改版?

Trawl 通过监控数据填充率(低于70%时触发)自动重新推导提取策略。LLM 仅需在每个网站结构变化时调用一次,后续抓取由高效的 Go 引擎执行,无需额外 API 费用。

安装 Trawl 最简单的方法是什么?

使用安装脚本最简便:执行 curl -fsSL https://raw.githubusercontent.com/akdavidsson/trawl/main/install.sh | sh 即可一键安装,无需手动配置环境。

Trawl 如何处理需要 JavaScript 渲染的页面?

使用 --js 标志时,Trawl 会启动无头浏览器自动等待 DOM 稳定、滚动页面触发懒加载,并点击“显示更多”按钮,确保动态内容完全渲染后再提取数据。

← 返回文章列表
分享到:微博

版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。

文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。

若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。 也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。