# HTML Text Extraction

> 借助 trafilatura 的内容边界检测，从 HTML 或 XHTML 文档中抽取主要可读内容。

Source: https://docs.sommatic.ai/zh/nodes/ai.html.extract.text/

- 标识: `ai.html.extract.text`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

借助 trafilatura 的内容边界检测，从 HTML 或 XHTML 文档中抽取主要可读内容。

去除导航框架、脚本、样式块、广告容器、Cookie 横幅、页眉、页脚和评论区，同时保留实质性的正文内容。

**功能特性：**
- **样板内容清除：** 基于 trafilatura 训练好的抽取器检测并移除页面框架，针对现代 CMS 和博客版面做了调优。
- **结构保留：** 按文档顺序保留标题、段落、有序和无序列表以及引用块。
- **精确率/召回率权衡：** `favor_precision` 可在激进清理（默认，误判更少）和宽松抽取（在非常规版面中找回内容）之间切换。
- **元数据抽取：** 若页面的 meta 标签、Open Graph 或 JSON-LD 中提供，则提取标题、规范 URL、作者、发布日期、站点名称和语言。
- **输入：** 接受原始 HTML 字符串、base64 编码的 HTML 或本地文件路径。

## 配置

- `favor_precision` (boolean, 可选): 以召回率换取精确率。若内容被截断，请关闭此项。 默认值: `true`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Extracted
- `empty`: Empty
- `error`: Error

## 输入契约

- `content` (string, 可选): 原始 HTML 字符串。
- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

- `text` (string, 可选)
- `chars` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)

## 在表达式中

后续节点可通过 `$("HTML Text Extraction").item.json.<路径>` 读取此节点输出中的内容（请把 `HTML Text Extraction` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("HTML Text Extraction").item.json.text` (string) = `"Release notes\nThe new version adds export t…"`
- `$("HTML Text Extraction").item.json.chars` (number) = `48`
- `$("HTML Text Extraction").item.json.empty` (boolean) = `false`
- `$("HTML Text Extraction").item.json.method` (string) = `"trafilatura"`
- `$("HTML Text Extraction").item.json.metadata` (object) = `{…}`
- `$("HTML Text Extraction").item.json.metadata.input_chars` (number) = `18342` (编辑器不提示)


## 工作原理

使用 trafilatura 提取 HTML 文档中的主要可读文本，去除导航、脚本、评论等样板内容；保留表格。

1. 从节点配置读取 `content`（原始 HTML 字符串）、`content_base64` 和 `file_path`，缺失时回退到上游载荷；三者都没有时从 `error` 输出。
2. 按以下顺序使用第一个存在的来源：`content`、`content_base64`（按 UTF-8 解码）、`file_path`。
3. 运行 trafilatura：排除评论、包含表格、不保留格式，`favor_precision` 取自配置（默认 `true`）。
4. 未提取到文本时从 `empty` 输出，否则从 `extracted` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-clean-page",
  "label": "Clean page",
  "operator_slug": "ai.html.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "content": "{{ $json.body }}",
    "favor_precision": true,
    "execution": {
      "timeout_ms": 60000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "text": "Release notes\nThe new version adds export to CSV.",
    "chars": 48,
    "empty": false,
    "method": "trafilatura",
    "metadata": {
      "input_chars": 18342
    }
  },
  "port": "extracted"
}
```

## 输出端口 (代码中的行为)

### `extracted`

找到了主要文本。

```json
{
  "text": "Release notes\nThe new version adds export to CSV.",
  "chars": 48,
  "empty": false,
  "method": "trafilatura",
  "metadata": {
    "input_chars": 18342
  }
}
```

### `empty`

trafilatura 未找到主要内容（页面过短或几乎全是导航）。

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "trafilatura",
  "metadata": {
    "input_chars": 412
  }
}
```

### `error`

未提供输入或脚本失败。

```json
{
  "error": "content, content_base64, or file_path is required.",
  "stderr": ""
}
```

## 代码中的行为

- `content, content_base64, file_path`: 未在配置 schema 中声明，但会先从节点配置读取，再从上游载荷读取。通常用表达式从上一个节点映射。
- `favor_precision`: 只有 `false` 会关闭；其他任何值（包括未设置）都保持精确模式。若真实内容被截断，请关闭它。
- `execution`: 仅读取 `execution.timeout_ms`（缺省回退 60000 毫秒）。`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail` 和 `alwaysOutputData` 均被忽略。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `content, content_base64, or file_path is required.` | `error` | 配置和上游载荷中都没有这三个来源中的任何一个。 |
| `Either content, content_base64, or file_path is required` | `error` | 当只提供了 `file_path` 而主机上不存在该文件时由脚本抛出。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超出了节点超时。请调大 `execution.timeout_ms` 或发送更小的文件。 |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | 结果（文本或 base64 文件）超过 50 MB 上限。请在上游拆分输入。 |
| `Python runtime not available (ENOENT)` | `error` | 主机上没有 Python 解释器。若依赖安装失败，消息为 `PythonRunner failed: <message>`。两者都是主机问题，而非工作流问题。 |

## 说明与限制

- 在子进程中运行 Python 脚本。某台 worker 主机上的首次运行会创建虚拟环境并安装脚本锁定的依赖（可能耗时数分钟，且不计入节点超时）；之后的运行会复用该环境。
- `file_path` 必须指向运行该节点的编排器主机本地磁盘上的文件；它不是 URL，也不会从存储中下载。
- 脚本会在 `execution.timeout_ms` 到期后被终止；未设置该键时代码使用 60000 毫秒，而不是 schema 默认的 300000。
- 本节点不会抓取 URL；请传入上游节点已下载的 HTML。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.html.extract.text",
  "name": "HTML Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts the main readable content from HTML or XHTML documents using trafilatura with content-boundary detection.\n\n  Strips navigation chrome, scripts, style blocks, advertising containers, cookie banners, headers, footers, and comment threads while preserving the substantive article body.\n\n  **Features:**\n  - **Boilerplate removal:** Detects and removes page chrome based on trafilatura's trained extractors, tuned for modern CMS and blog layouts.\n  - **Structural preservation:** Retains headings, paragraphs, ordered and unordered lists, and blockquotes in document order.\n  - **Precision/recall tradeoff:** `favor_precision` toggles between aggressive cleanup (default, fewer false positives) and permissive extraction (recovers content on unconventional layouts).\n  - **Metadata extraction:** Pulls title, canonical URL, author, publish date, site name, and language when surfaced by the page's meta tags, Open Graph, or JSON-LD.\n  - **Inputs:** Accepts raw HTML as a string, base64-encoded HTML, or a local file path.",
  "capabilities": [
    "html",
    "xhtml",
    "markup",
    "text-extraction"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "favor_precision": {
        "type": "boolean",
        "title": "Favor Precision",
        "default": true,
        "description": "Trade recall for precision. Turn off if content is getting truncated."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content": {
        "type": "string",
        "description": "Raw HTML string."
      },
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "html",
    "text",
    "markup"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "favor_precision": {
      "type": "boolean",
      "title": "Favor Precision",
      "default": true,
      "description": "Trade recall for precision. Turn off if content is getting truncated."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content": {
      "type": "string",
      "description": "Raw HTML string."
    },
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
