pialuo 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pialuo-0.1.0/LICENSE +21 -0
- pialuo-0.1.0/PKG-INFO +111 -0
- pialuo-0.1.0/README.md +87 -0
- pialuo-0.1.0/pialuo/__init__.py +19 -0
- pialuo-0.1.0/pialuo/__main__.py +9 -0
- pialuo-0.1.0/pialuo/core.py +666 -0
- pialuo-0.1.0/pialuo/mcp.py +116 -0
- pialuo-0.1.0/pialuo.egg-info/PKG-INFO +111 -0
- pialuo-0.1.0/pialuo.egg-info/SOURCES.txt +12 -0
- pialuo-0.1.0/pialuo.egg-info/dependency_links.txt +1 -0
- pialuo-0.1.0/pialuo.egg-info/entry_points.txt +3 -0
- pialuo-0.1.0/pialuo.egg-info/top_level.txt +1 -0
- pialuo-0.1.0/pyproject.toml +36 -0
- pialuo-0.1.0/setup.cfg +4 -0
pialuo-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tanbopiao / zongyuangen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pialuo-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pialuo
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 爬罗剔抉 pialuo — 轻量网页抓取与结构化提取算子:纯标准库零依赖,内存个位数 MB(提炼自 Crawl4AI 核心思路)
|
|
5
|
+
Author: tanbopiao
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitcode.com/zongyuangen/pialuo
|
|
8
|
+
Project-URL: Repository, https://github.com/tanbopiao/pialuo
|
|
9
|
+
Keywords: crawler,web-scraping,llm,mcp,extractor,yuanshu
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
19
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pialuo —— 爬罗剔抉,刮垢磨光
|
|
26
|
+
|
|
27
|
+
轻量化网页抓取与内容提炼算子。抓取网页、按文本密度剪枝去噪,输出 LLM 友好的
|
|
28
|
+
Markdown 或按 CSS 选择器 schema 提取结构化 JSON。
|
|
29
|
+
|
|
30
|
+
> 名字取自韩愈《进学解》:"爬罗剔抉,刮垢磨光"——爬罗(搜集)剔抉(挑选),
|
|
31
|
+
> 正是"抓取→清洗→提炼"这件事。
|
|
32
|
+
|
|
33
|
+
纯 Python 标准库实现,零第三方依赖,单文件 666 行。
|
|
34
|
+
|
|
35
|
+
## 用法
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
# 抓取并输出清洗后的 Markdown
|
|
39
|
+
python pialuo.py https://www.python.org/
|
|
40
|
+
|
|
41
|
+
# 输出到文件,显示耗时与内存
|
|
42
|
+
python pialuo.py https://www.python.org/ --out page.md --profile
|
|
43
|
+
|
|
44
|
+
# 按 schema 提取结构化 JSON(无需 LLM)
|
|
45
|
+
python pialuo.py https://www.python.org/ --schema schema.json
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
schema 格式(JsonCss 风格):
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"baseSelector": "ul.menu li",
|
|
53
|
+
"fields": [
|
|
54
|
+
{"name": "title", "selector": "a", "type": "text"},
|
|
55
|
+
{"name": "url", "selector": "a", "type": "attribute", "attribute": "href"}
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
选择器支持子集:`tag`、`.class`、`#id`、后代空格组合。
|
|
61
|
+
|
|
62
|
+
## MCP 服务
|
|
63
|
+
|
|
64
|
+
仓库内 `mcp_server.py` 提供 JSON-RPC 2.0 over stdio 的 MCP 服务(零依赖),
|
|
65
|
+
任何支持 MCP 的客户端可直接接入:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
python mcp_server.py
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
工具:
|
|
72
|
+
- `fetch_page(url, timeout?, retries?, word_threshold?)` —— 抓取网页并清洗为 LLM 友好 Markdown;
|
|
73
|
+
- `extract_structured(url, schema)` —— 按 JsonCss 风格 schema 做结构化提取,无需 LLM。
|
|
74
|
+
|
|
75
|
+
## 与 Crawl4AI 的取舍对比
|
|
76
|
+
|
|
77
|
+
| 维度 | Crawl4AI(上游) | pialuo(本算子) |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| 定位 | 全功能 Agent 爬取框架 | 单一算子:抓取→清洗→提取 |
|
|
80
|
+
| 代码形态 | 543 个 py 文件、约 15.6 万行 | 单文件 666 行 |
|
|
81
|
+
| 依赖 | 25+(Playwright、numpy、litellm 等) | 0(纯标准库) |
|
|
82
|
+
| 部署形态 | Docker 镜像 8.2GB,要求 4GB RAM | 一个 py 文件直接跑 |
|
|
83
|
+
| 空闲内存 | 538MB(实测) | 进程 RSS 峰值约 25MB(含解释器基线),解析 51KB 页面 tracemalloc 峰值 0.78MB |
|
|
84
|
+
| 51KB 页面处理耗时 | — | 解析+剪枝+渲染 78ms |
|
|
85
|
+
| 抓取调度 | asyncio 并发/重试/robots/缓存 | 同步抓取/重试/robots(缓存砍掉) |
|
|
86
|
+
| 文本密度剪枝 | PruningContentFilter | 同思路自研:分词噪音匹配 + 词数阈值 + 链接密度 |
|
|
87
|
+
| 结构化提取 | JsonCss/JsonXPath + LLM 策略 | JsonCss 子集(LLM 策略砍掉) |
|
|
88
|
+
| 浏览器/JS 执行 | Playwright/patchright 双栈 | 无——动态渲染页面拿不到正文 |
|
|
89
|
+
| Docker API 服务层 | 1211 行 server.py(上游漏洞聚集地) | 无此层,攻击面不存在 |
|
|
90
|
+
| CLI/Web UI/MCP/PDF/代理/深爬取 | 有 | 全部砍掉 |
|
|
91
|
+
|
|
92
|
+
**功能对齐的核心场景**:静态页抓取 → 去导航/页脚/广告 → LLM 友好 Markdown;
|
|
93
|
+
CSS 选择器 schema → 结构化 JSON。实测 python.org 首页:新闻列表、成功故事、
|
|
94
|
+
PSF 介绍等正文完整保留,导航/横幅/脚本剔除。
|
|
95
|
+
|
|
96
|
+
**如实边界**:需要 JS 渲染的页面(如 Bing 首页搜索结果)拿不到正文;
|
|
97
|
+
无浏览器、无 JS 执行、无并发调度、无缓存、无代理轮换。
|
|
98
|
+
|
|
99
|
+
## 理念致谢
|
|
100
|
+
|
|
101
|
+
本项目功能、架构与逻辑思路致谢 [Crawl4AI](https://github.com/unclecode/crawl4ai)
|
|
102
|
+
(Apache-2.0)。本仓库为**独立重写,无任何上游代码血缘**;依 Crawl4AI 许可证之
|
|
103
|
+
Attribution Requirement,公开分发时注明出处如上。
|
|
104
|
+
|
|
105
|
+
## 复刻哲学
|
|
106
|
+
|
|
107
|
+
外来佳作功能、架构、逻辑皆可复刻,算子代码必自研完善;收编先深扫,复刻必致谢,轻量一个量级。
|
|
108
|
+
|
|
109
|
+
## 许可证
|
|
110
|
+
|
|
111
|
+
MIT(见 LICENSE)。
|
pialuo-0.1.0/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# pialuo —— 爬罗剔抉,刮垢磨光
|
|
2
|
+
|
|
3
|
+
轻量化网页抓取与内容提炼算子。抓取网页、按文本密度剪枝去噪,输出 LLM 友好的
|
|
4
|
+
Markdown 或按 CSS 选择器 schema 提取结构化 JSON。
|
|
5
|
+
|
|
6
|
+
> 名字取自韩愈《进学解》:"爬罗剔抉,刮垢磨光"——爬罗(搜集)剔抉(挑选),
|
|
7
|
+
> 正是"抓取→清洗→提炼"这件事。
|
|
8
|
+
|
|
9
|
+
纯 Python 标准库实现,零第三方依赖,单文件 666 行。
|
|
10
|
+
|
|
11
|
+
## 用法
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
# 抓取并输出清洗后的 Markdown
|
|
15
|
+
python pialuo.py https://www.python.org/
|
|
16
|
+
|
|
17
|
+
# 输出到文件,显示耗时与内存
|
|
18
|
+
python pialuo.py https://www.python.org/ --out page.md --profile
|
|
19
|
+
|
|
20
|
+
# 按 schema 提取结构化 JSON(无需 LLM)
|
|
21
|
+
python pialuo.py https://www.python.org/ --schema schema.json
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
schema 格式(JsonCss 风格):
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"baseSelector": "ul.menu li",
|
|
29
|
+
"fields": [
|
|
30
|
+
{"name": "title", "selector": "a", "type": "text"},
|
|
31
|
+
{"name": "url", "selector": "a", "type": "attribute", "attribute": "href"}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
选择器支持子集:`tag`、`.class`、`#id`、后代空格组合。
|
|
37
|
+
|
|
38
|
+
## MCP 服务
|
|
39
|
+
|
|
40
|
+
仓库内 `mcp_server.py` 提供 JSON-RPC 2.0 over stdio 的 MCP 服务(零依赖),
|
|
41
|
+
任何支持 MCP 的客户端可直接接入:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
python mcp_server.py
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
工具:
|
|
48
|
+
- `fetch_page(url, timeout?, retries?, word_threshold?)` —— 抓取网页并清洗为 LLM 友好 Markdown;
|
|
49
|
+
- `extract_structured(url, schema)` —— 按 JsonCss 风格 schema 做结构化提取,无需 LLM。
|
|
50
|
+
|
|
51
|
+
## 与 Crawl4AI 的取舍对比
|
|
52
|
+
|
|
53
|
+
| 维度 | Crawl4AI(上游) | pialuo(本算子) |
|
|
54
|
+
|---|---|---|
|
|
55
|
+
| 定位 | 全功能 Agent 爬取框架 | 单一算子:抓取→清洗→提取 |
|
|
56
|
+
| 代码形态 | 543 个 py 文件、约 15.6 万行 | 单文件 666 行 |
|
|
57
|
+
| 依赖 | 25+(Playwright、numpy、litellm 等) | 0(纯标准库) |
|
|
58
|
+
| 部署形态 | Docker 镜像 8.2GB,要求 4GB RAM | 一个 py 文件直接跑 |
|
|
59
|
+
| 空闲内存 | 538MB(实测) | 进程 RSS 峰值约 25MB(含解释器基线),解析 51KB 页面 tracemalloc 峰值 0.78MB |
|
|
60
|
+
| 51KB 页面处理耗时 | — | 解析+剪枝+渲染 78ms |
|
|
61
|
+
| 抓取调度 | asyncio 并发/重试/robots/缓存 | 同步抓取/重试/robots(缓存砍掉) |
|
|
62
|
+
| 文本密度剪枝 | PruningContentFilter | 同思路自研:分词噪音匹配 + 词数阈值 + 链接密度 |
|
|
63
|
+
| 结构化提取 | JsonCss/JsonXPath + LLM 策略 | JsonCss 子集(LLM 策略砍掉) |
|
|
64
|
+
| 浏览器/JS 执行 | Playwright/patchright 双栈 | 无——动态渲染页面拿不到正文 |
|
|
65
|
+
| Docker API 服务层 | 1211 行 server.py(上游漏洞聚集地) | 无此层,攻击面不存在 |
|
|
66
|
+
| CLI/Web UI/MCP/PDF/代理/深爬取 | 有 | 全部砍掉 |
|
|
67
|
+
|
|
68
|
+
**功能对齐的核心场景**:静态页抓取 → 去导航/页脚/广告 → LLM 友好 Markdown;
|
|
69
|
+
CSS 选择器 schema → 结构化 JSON。实测 python.org 首页:新闻列表、成功故事、
|
|
70
|
+
PSF 介绍等正文完整保留,导航/横幅/脚本剔除。
|
|
71
|
+
|
|
72
|
+
**如实边界**:需要 JS 渲染的页面(如 Bing 首页搜索结果)拿不到正文;
|
|
73
|
+
无浏览器、无 JS 执行、无并发调度、无缓存、无代理轮换。
|
|
74
|
+
|
|
75
|
+
## 理念致谢
|
|
76
|
+
|
|
77
|
+
本项目功能、架构与逻辑思路致谢 [Crawl4AI](https://github.com/unclecode/crawl4ai)
|
|
78
|
+
(Apache-2.0)。本仓库为**独立重写,无任何上游代码血缘**;依 Crawl4AI 许可证之
|
|
79
|
+
Attribution Requirement,公开分发时注明出处如上。
|
|
80
|
+
|
|
81
|
+
## 复刻哲学
|
|
82
|
+
|
|
83
|
+
外来佳作功能、架构、逻辑皆可复刻,算子代码必自研完善;收编先深扫,复刻必致谢,轻量一个量级。
|
|
84
|
+
|
|
85
|
+
## 许可证
|
|
86
|
+
|
|
87
|
+
MIT(见 LICENSE)。
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""爬罗剔抉 pialuo —— 轻量网页抓取与结构化提取算子
|
|
3
|
+
|
|
4
|
+
道统铭文:爬罗剔抉,刮垢磨光(韩愈《进学解》)
|
|
5
|
+
提炼自 Crawl4AI 的「抓取→清洗→结构化提取」核心思路,
|
|
6
|
+
零第三方依赖(纯标准库),单次抓取内存占用为个位数 MB 量级。
|
|
7
|
+
边界:无浏览器无 JS,动态渲染页拿不到正文。
|
|
8
|
+
"""
|
|
9
|
+
from .core import ( # noqa: F401
|
|
10
|
+
extract,
|
|
11
|
+
fetch,
|
|
12
|
+
main,
|
|
13
|
+
parse_html,
|
|
14
|
+
prune_tree,
|
|
15
|
+
select,
|
|
16
|
+
to_markdown,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
pialuo —— 爬罗剔抉,刮垢磨光(韩愈《进学解》)
|
|
5
|
+
|
|
6
|
+
轻量化网页抓取与内容提炼算子。理念致谢 Crawl4AI(Apache-2.0):
|
|
7
|
+
本文件为独立重写,无任何上游代码血缘;只提炼其核心编排逻辑——
|
|
8
|
+
抓取调度(重试/robots)、文本密度剪枝清洗、CSS 选择器结构化提取。
|
|
9
|
+
|
|
10
|
+
设计取舍(对齐轻量化复刻标准):
|
|
11
|
+
- 纯标准库(urllib / html.parser / re / json),零第三方依赖;
|
|
12
|
+
- 无浏览器、无 JS 执行:动态渲染页面拿不到正文,边界如实;
|
|
13
|
+
- 单文件、函数直调,不引框架;
|
|
14
|
+
- 密钥凭据不入档:本文件不读取、不存储任何凭据。
|
|
15
|
+
|
|
16
|
+
用法:
|
|
17
|
+
python pialuo.py <url> [--schema schema.json] [--out out.md] [--json]
|
|
18
|
+
[--timeout 20] [--retries 2] [--no-robots]
|
|
19
|
+
[--word-threshold 40] [--profile]
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.parse
|
|
29
|
+
import urllib.request
|
|
30
|
+
import urllib.robotparser
|
|
31
|
+
from html.parser import HTMLParser
|
|
32
|
+
|
|
33
|
+
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
34
|
+
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36")
|
|
35
|
+
|
|
36
|
+
# ============================================================================
|
|
37
|
+
# 一、DOM 树:比 html.parser 事件模型更好用的轻量树
|
|
38
|
+
# ============================================================================
|
|
39
|
+
|
|
40
|
+
# 不产生子节点的空元素(HTML5 规范)
|
|
41
|
+
VOID_TAGS = {
|
|
42
|
+
"area", "base", "br", "col", "embed", "hr", "img", "input",
|
|
43
|
+
"link", "meta", "param", "source", "track", "wbr",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Node:
|
|
48
|
+
"""极简 DOM 节点。#text 为文本节点,#root 为虚拟根。"""
|
|
49
|
+
|
|
50
|
+
__slots__ = ("tag", "attrs", "parent", "children", "text")
|
|
51
|
+
|
|
52
|
+
def __init__(self, tag, attrs=None, parent=None, text=""):
|
|
53
|
+
self.tag = tag
|
|
54
|
+
self.attrs = dict(attrs or {})
|
|
55
|
+
self.parent = parent
|
|
56
|
+
self.children = []
|
|
57
|
+
self.text = text # 仅 #text 节点使用
|
|
58
|
+
|
|
59
|
+
def get(self, name, default=None):
|
|
60
|
+
return self.attrs.get(name, default)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TreeBuilder(HTMLParser):
|
|
64
|
+
"""把 HTML 解析为 Node 树。对错配标签做容错:栈内就近匹配。"""
|
|
65
|
+
|
|
66
|
+
def __init__(self):
|
|
67
|
+
# convert_charrefs=True:实体(& 等)自动转成字符
|
|
68
|
+
super().__init__(convert_charrefs=True)
|
|
69
|
+
self.root = Node("#root")
|
|
70
|
+
self.stack = [self.root]
|
|
71
|
+
|
|
72
|
+
def handle_starttag(self, tag, attrs):
|
|
73
|
+
node = Node(tag, attrs, parent=self.stack[-1])
|
|
74
|
+
self.stack[-1].children.append(node)
|
|
75
|
+
if tag not in VOID_TAGS:
|
|
76
|
+
self.stack.append(node)
|
|
77
|
+
|
|
78
|
+
def handle_startendtag(self, tag, attrs):
|
|
79
|
+
node = Node(tag, attrs, parent=self.stack[-1])
|
|
80
|
+
self.stack[-1].children.append(node)
|
|
81
|
+
|
|
82
|
+
def handle_endtag(self, tag):
|
|
83
|
+
# 容错:从栈顶向下找最近的同名开标签;找不到就忽略(如 </p> 多余)
|
|
84
|
+
for i in range(len(self.stack) - 1, 0, -1):
|
|
85
|
+
if self.stack[i].tag == tag:
|
|
86
|
+
del self.stack[i:]
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
def handle_data(self, data):
|
|
90
|
+
if data:
|
|
91
|
+
node = Node("#text", parent=self.stack[-1], text=data)
|
|
92
|
+
self.stack[-1].children.append(node)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_html(html):
|
|
96
|
+
builder = TreeBuilder()
|
|
97
|
+
try:
|
|
98
|
+
builder.feed(html)
|
|
99
|
+
builder.close()
|
|
100
|
+
except Exception:
|
|
101
|
+
# html.parser 对极端残缺页面也可能抛错;尽力保留已解析部分
|
|
102
|
+
pass
|
|
103
|
+
return builder.root
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def iter_elements(node):
|
|
107
|
+
"""先序遍历所有元素节点(跳过 #text / #root)。"""
|
|
108
|
+
for child in node.children:
|
|
109
|
+
if child.tag != "#text":
|
|
110
|
+
yield child
|
|
111
|
+
yield from iter_elements(child)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def get_text(node):
|
|
115
|
+
"""收集节点内全部文本,空白归一。"""
|
|
116
|
+
parts = []
|
|
117
|
+
|
|
118
|
+
def walk(n):
|
|
119
|
+
if n.tag == "#text":
|
|
120
|
+
parts.append(n.text)
|
|
121
|
+
else:
|
|
122
|
+
if n.tag == "br":
|
|
123
|
+
parts.append(" ")
|
|
124
|
+
for c in n.children:
|
|
125
|
+
walk(c)
|
|
126
|
+
|
|
127
|
+
walk(node)
|
|
128
|
+
return re.sub(r"\s+", " ", "".join(parts)).strip()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def classes(node):
|
|
132
|
+
return set((node.get("class") or "").split())
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def serialize(node):
|
|
136
|
+
"""把子树还原为 HTML 字符串(供 schema 的 html 类型字段用)。"""
|
|
137
|
+
if node.tag == "#text":
|
|
138
|
+
return node.text
|
|
139
|
+
attrs = "".join(
|
|
140
|
+
' {}="{}"'.format(k, v.replace('"', """))
|
|
141
|
+
for k, v in node.attrs.items()
|
|
142
|
+
)
|
|
143
|
+
inner = "".join(serialize(c) for c in node.children)
|
|
144
|
+
if node.tag in VOID_TAGS:
|
|
145
|
+
return "<{}{}>".format(node.tag, attrs)
|
|
146
|
+
return "<{}{}>{}</{}>".format(node.tag, attrs, inner, node.tag)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ============================================================================
|
|
150
|
+
# 二、CSS 选择器子集:tag / .class / #id / 后代空格组合
|
|
151
|
+
# ============================================================================
|
|
152
|
+
|
|
153
|
+
_SIMPLE_RE = re.compile(r"^([a-zA-Z][\w-]*|\*)?((?:[.#][\w-]+)*)$")
|
|
154
|
+
_CONST_RE = re.compile(r"[.#][\w-]+")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def parse_selector(selector):
|
|
158
|
+
"""'div.article p.title' → [(tag, [约束]), ...] 从左到右。"""
|
|
159
|
+
parts = []
|
|
160
|
+
for token in selector.split():
|
|
161
|
+
m = _SIMPLE_RE.match(token)
|
|
162
|
+
if not m:
|
|
163
|
+
raise ValueError("不支持的选择器片段: %r" % token)
|
|
164
|
+
tag = m.group(1)
|
|
165
|
+
cons = _CONST_RE.findall(m.group(2) or "")
|
|
166
|
+
parts.append((tag.lower() if tag and tag != "*" else tag, cons))
|
|
167
|
+
return parts
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _matches_simple(el, tag, cons):
|
|
171
|
+
if tag and tag != "*" and el.tag != tag:
|
|
172
|
+
return False
|
|
173
|
+
for c in cons:
|
|
174
|
+
if c.startswith("."):
|
|
175
|
+
if c[1:] not in classes(el):
|
|
176
|
+
return False
|
|
177
|
+
elif c.startswith("#"):
|
|
178
|
+
if el.get("id") != c[1:]:
|
|
179
|
+
return False
|
|
180
|
+
return True
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _matches_chain(el, parts):
|
|
184
|
+
"""后代组合匹配:末段匹配自身,其余段匹配任意祖先。"""
|
|
185
|
+
if not parts:
|
|
186
|
+
return True
|
|
187
|
+
tag, cons = parts[-1]
|
|
188
|
+
if not _matches_simple(el, tag, cons):
|
|
189
|
+
return False
|
|
190
|
+
rest = parts[:-1]
|
|
191
|
+
if not rest:
|
|
192
|
+
return True
|
|
193
|
+
p = el.parent
|
|
194
|
+
while p is not None and p.tag != "#root":
|
|
195
|
+
if _matches_chain(p, rest):
|
|
196
|
+
return True
|
|
197
|
+
p = p.parent
|
|
198
|
+
return False
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def select(root, selector):
|
|
202
|
+
parts = parse_selector(selector)
|
|
203
|
+
return [el for el in iter_elements(root) if _matches_chain(el, parts)]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# ============================================================================
|
|
207
|
+
# 三、内容清洗:文本密度剪枝 → LLM 友好 Markdown
|
|
208
|
+
# 对齐上游 PruningContentFilter 思路:按节点文本密度打分,
|
|
209
|
+
# 剔除导航/页脚/广告/脚本样式;word_count_threshold 控制剪枝粒度。
|
|
210
|
+
# ============================================================================
|
|
211
|
+
|
|
212
|
+
# 整体剔除的标签:无正文价值
|
|
213
|
+
STRIP_TAGS = {
|
|
214
|
+
"script", "style", "noscript", "template", "svg", "iframe",
|
|
215
|
+
"canvas", "link", "meta", "form", "button", "select", "option",
|
|
216
|
+
"dialog", "video", "audio", "object", "embed",
|
|
217
|
+
}
|
|
218
|
+
# 结构性噪音标签:导航/页脚等
|
|
219
|
+
STRUCT_TAGS = {"nav", "header", "footer", "aside"}
|
|
220
|
+
# class/id 命中即视为噪音(导航、广告、分享条、面包屑……)。
|
|
221
|
+
# 按分词精确匹配:class/id 以空白、-、_ 切分后比对词表,
|
|
222
|
+
# 避免子串误伤(如 id="touchnav-wrapper" 含 "nav" 但并非导航)。
|
|
223
|
+
NOISE_TOKENS = {
|
|
224
|
+
"nav", "navbar", "topnav", "subnav", "sidenav", "sidebar",
|
|
225
|
+
"footer", "header", "comment", "comments", "advert", "advertisement",
|
|
226
|
+
"ad", "ads", "banner", "social", "share", "sharing", "related",
|
|
227
|
+
"breadcrumb", "breadcrumbs", "pagination", "promo", "promotion",
|
|
228
|
+
"subscribe", "newsletter", "cookie", "cookies", "popup", "modal",
|
|
229
|
+
"donate", "sponsor", "sponsorship",
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _is_noise_node(el):
|
|
234
|
+
ident = " ".join([el.get("class") or "", el.get("id") or ""])
|
|
235
|
+
if not ident.strip():
|
|
236
|
+
return False
|
|
237
|
+
tokens = set(re.split(r"[\s_\-]+", ident.lower()))
|
|
238
|
+
return bool(tokens & NOISE_TOKENS)
|
|
239
|
+
# 小文本也不剪的有意义标签
|
|
240
|
+
KEEP_SMALL = {
|
|
241
|
+
"h1", "h2", "h3", "h4", "h5", "h6", "li", "td", "th",
|
|
242
|
+
"blockquote", "figcaption", "dt", "dd", "caption", "pre", "code",
|
|
243
|
+
"title",
|
|
244
|
+
}
|
|
245
|
+
# 行内元素:依附于所在块,不参与块级剪枝(否则段落里的链接会被误剪)
|
|
246
|
+
INLINE_TAGS = {
|
|
247
|
+
"a", "code", "strong", "em", "b", "i", "u", "span", "small",
|
|
248
|
+
"sup", "sub", "abbr", "time", "mark", "kbd", "samp", "cite", "q",
|
|
249
|
+
}
|
|
250
|
+
# 容器标签:自身不直接产文本,文本来自子节点,不参与"小文本剪枝"
|
|
251
|
+
# (否则 ul/table/head 会被整棵误剪——它们的文本都在 KEEP_SMALL 子节点里)
|
|
252
|
+
CONTAINER_TAGS = {
|
|
253
|
+
"html", "head", "body", "article", "section", "main", "div",
|
|
254
|
+
"ul", "ol", "table", "thead", "tbody", "tfoot", "tr", "dl", "figure",
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _count_words(text):
|
|
259
|
+
"""词数统计:拉丁文按词、中文按字(对齐上游 word_count_threshold 语义)。"""
|
|
260
|
+
latin = len(re.findall(r"[A-Za-z0-9]+", text))
|
|
261
|
+
cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
|
|
262
|
+
return latin + cjk
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _subtree_stats(node):
|
|
266
|
+
"""返回 (总文本长度, 链接文本长度, 子树词数)。"""
|
|
267
|
+
total, link = 0, 0
|
|
268
|
+
|
|
269
|
+
def walk(n, in_link):
|
|
270
|
+
nonlocal total, link
|
|
271
|
+
if n.tag == "#text":
|
|
272
|
+
t = len(n.text)
|
|
273
|
+
total += t
|
|
274
|
+
if in_link:
|
|
275
|
+
link += t
|
|
276
|
+
return
|
|
277
|
+
for c in n.children:
|
|
278
|
+
walk(c, in_link or c.tag == "a")
|
|
279
|
+
|
|
280
|
+
walk(node, False)
|
|
281
|
+
words = _count_words(get_text(node))
|
|
282
|
+
return total, link, words
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def prune_tree(root, word_count_threshold=10):
|
|
286
|
+
"""两轮剪枝:① 标签/类名规则剔除;② 文本密度打分剔除。
|
|
287
|
+
word_count_threshold 按词计(拉丁文按词、中文按字),对齐上游语义。"""
|
|
288
|
+
|
|
289
|
+
def drop(node):
|
|
290
|
+
if node.parent is not None:
|
|
291
|
+
node.parent.children.remove(node)
|
|
292
|
+
node.parent = None
|
|
293
|
+
|
|
294
|
+
# ① 规则剔除
|
|
295
|
+
for el in list(iter_elements(root)):
|
|
296
|
+
if el.parent is None:
|
|
297
|
+
continue # 已被父级连带剔除
|
|
298
|
+
if el.tag in STRIP_TAGS or el.tag in STRUCT_TAGS:
|
|
299
|
+
drop(el)
|
|
300
|
+
continue
|
|
301
|
+
if _is_noise_node(el):
|
|
302
|
+
drop(el)
|
|
303
|
+
|
|
304
|
+
# ② 密度打分:自底向上,低密度节点剪掉
|
|
305
|
+
for el in list(iter_elements(root)):
|
|
306
|
+
if el.parent is None or el.tag == "#text":
|
|
307
|
+
continue
|
|
308
|
+
total, link, words = _subtree_stats(el)
|
|
309
|
+
link_ratio = link / total if total else 0.0
|
|
310
|
+
# 行内元素豁免块级剪枝
|
|
311
|
+
if el.tag in INLINE_TAGS:
|
|
312
|
+
continue
|
|
313
|
+
# 链接占比过高的短块(导航/目录特征)→ 剪(KEEP_SMALL 除外)
|
|
314
|
+
if el.tag not in KEEP_SMALL and link_ratio > 0.6 and total < 200:
|
|
315
|
+
drop(el)
|
|
316
|
+
continue
|
|
317
|
+
# 容器与有意义标签不参与小文本剪枝
|
|
318
|
+
if el.tag in KEEP_SMALL or el.tag in CONTAINER_TAGS:
|
|
319
|
+
continue
|
|
320
|
+
# 文本太少的叶子块(低于阈值)→ 剪
|
|
321
|
+
if words < word_count_threshold:
|
|
322
|
+
drop(el)
|
|
323
|
+
|
|
324
|
+
# 清掉空壳节点(无文本无可见子元素)
|
|
325
|
+
def clean(n):
|
|
326
|
+
for c in list(n.children):
|
|
327
|
+
clean(c)
|
|
328
|
+
if c.tag != "#text" and not c.children and c.tag not in VOID_TAGS:
|
|
329
|
+
n.children.remove(c)
|
|
330
|
+
|
|
331
|
+
clean(root)
|
|
332
|
+
return root
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ---- Markdown 渲染 --------------------------------------------------------
|
|
336
|
+
|
|
337
|
+
_BLOCK_TAGS = {
|
|
338
|
+
"p", "div", "section", "article", "main", "ul", "ol", "table",
|
|
339
|
+
"pre", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
|
|
340
|
+
"figure", "dl", "address",
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _render_inline(node, base_url):
|
|
345
|
+
"""行内内容:文本 + 链接 + 代码 + 换行。"""
|
|
346
|
+
if node.tag == "#text":
|
|
347
|
+
return node.text
|
|
348
|
+
if node.tag == "br":
|
|
349
|
+
return "\n"
|
|
350
|
+
if node.tag == "a":
|
|
351
|
+
text = "".join(_render_inline(c, base_url) for c in node.children).strip()
|
|
352
|
+
href = node.get("href")
|
|
353
|
+
if href and text:
|
|
354
|
+
abs_href = urllib.parse.urljoin(base_url, href.strip())
|
|
355
|
+
return "[%s](%s)" % (text, abs_href)
|
|
356
|
+
return text
|
|
357
|
+
if node.tag == "img":
|
|
358
|
+
# 图片对 LLM 阅读是噪音:丢弃,仅保留 alt 文本(如有)
|
|
359
|
+
return node.get("alt") or ""
|
|
360
|
+
inner = "".join(_render_inline(c, base_url) for c in node.children)
|
|
361
|
+
if node.tag in ("code", "kbd", "samp"):
|
|
362
|
+
return "`%s`" % inner if inner.strip() else inner
|
|
363
|
+
return inner
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _render_blocks(node, base_url, list_depth=0):
|
|
367
|
+
"""块级渲染:产出 Markdown 块列表。"""
|
|
368
|
+
blocks = []
|
|
369
|
+
for c in node.children:
|
|
370
|
+
if c.tag == "#text":
|
|
371
|
+
t = c.text.strip()
|
|
372
|
+
if t:
|
|
373
|
+
blocks.append(t)
|
|
374
|
+
continue
|
|
375
|
+
tag = c.tag
|
|
376
|
+
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
|
|
377
|
+
level = int(tag[1])
|
|
378
|
+
text = _render_inline(c, base_url).strip()
|
|
379
|
+
if text:
|
|
380
|
+
blocks.append("#" * level + " " + text)
|
|
381
|
+
elif tag == "p":
|
|
382
|
+
text = _render_inline(c, base_url).strip()
|
|
383
|
+
if text:
|
|
384
|
+
blocks.append(text)
|
|
385
|
+
elif tag in ("ul", "ol"):
|
|
386
|
+
lines = _render_list(c, base_url, list_depth)
|
|
387
|
+
if lines:
|
|
388
|
+
blocks.append("\n".join(lines))
|
|
389
|
+
elif tag == "pre":
|
|
390
|
+
code = get_text(c)
|
|
391
|
+
if code:
|
|
392
|
+
blocks.append("```\n%s\n```" % code)
|
|
393
|
+
elif tag == "blockquote":
|
|
394
|
+
text = _render_inline(c, base_url).strip()
|
|
395
|
+
if text:
|
|
396
|
+
blocks.append("> " + text)
|
|
397
|
+
elif tag == "table":
|
|
398
|
+
md = _render_table(c, base_url)
|
|
399
|
+
if md:
|
|
400
|
+
blocks.append(md)
|
|
401
|
+
elif tag == "hr":
|
|
402
|
+
blocks.append("---")
|
|
403
|
+
elif tag == "dl":
|
|
404
|
+
for item in c.children:
|
|
405
|
+
if item.tag == "dt":
|
|
406
|
+
t = _render_inline(item, base_url).strip()
|
|
407
|
+
if t:
|
|
408
|
+
blocks.append("**%s**" % t)
|
|
409
|
+
elif item.tag == "dd":
|
|
410
|
+
t = _render_inline(item, base_url).strip()
|
|
411
|
+
if t:
|
|
412
|
+
blocks.append(t)
|
|
413
|
+
elif tag == "figure":
|
|
414
|
+
blocks.extend(_render_blocks(c, base_url, list_depth))
|
|
415
|
+
else:
|
|
416
|
+
# div/section/article/main 等容器:递归展开
|
|
417
|
+
blocks.extend(_render_blocks(c, base_url, list_depth))
|
|
418
|
+
return blocks
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _render_list(list_node, base_url, depth):
|
|
422
|
+
lines = []
|
|
423
|
+
ordered = list_node.tag == "ol"
|
|
424
|
+
idx = 0
|
|
425
|
+
for li in list_node.children:
|
|
426
|
+
if li.tag != "li":
|
|
427
|
+
continue
|
|
428
|
+
idx += 1
|
|
429
|
+
marker = "%d. " % idx if ordered else "- "
|
|
430
|
+
# li 的直接行内内容(不含嵌套列表)
|
|
431
|
+
inner_parts = []
|
|
432
|
+
nested = []
|
|
433
|
+
for sub in li.children:
|
|
434
|
+
if sub.tag in ("ul", "ol"):
|
|
435
|
+
nested.append(sub)
|
|
436
|
+
else:
|
|
437
|
+
inner_parts.append(_render_inline(sub, base_url))
|
|
438
|
+
text = re.sub(r"\s+", " ", "".join(inner_parts)).strip()
|
|
439
|
+
indent = " " * depth
|
|
440
|
+
lines.append("%s%s%s" % (indent, marker, text))
|
|
441
|
+
for sub in nested:
|
|
442
|
+
lines.extend(_render_list(sub, base_url, depth + 1))
|
|
443
|
+
return lines
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _render_table(table, base_url):
|
|
447
|
+
rows = []
|
|
448
|
+
for tr in iter_elements(table):
|
|
449
|
+
if tr.tag != "tr":
|
|
450
|
+
continue
|
|
451
|
+
cells = [
|
|
452
|
+
_render_inline(td, base_url).strip().replace("|", "\\|")
|
|
453
|
+
for td in tr.children
|
|
454
|
+
if td.tag in ("td", "th")
|
|
455
|
+
]
|
|
456
|
+
if any(cells):
|
|
457
|
+
rows.append(cells)
|
|
458
|
+
if not rows:
|
|
459
|
+
return ""
|
|
460
|
+
width = max(len(r) for r in rows)
|
|
461
|
+
rows = [r + [""] * (width - len(r)) for r in rows]
|
|
462
|
+
out = ["| " + " | ".join(rows[0]) + " |", "|" + "---|" * width]
|
|
463
|
+
for r in rows[1:]:
|
|
464
|
+
out.append("| " + " | ".join(r) + " |")
|
|
465
|
+
return "\n".join(out)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def to_markdown(root, base_url=""):
|
|
469
|
+
"""清洗后的树 → LLM 友好 Markdown。文档标题作为一级标题。"""
|
|
470
|
+
# 提取 <title>
|
|
471
|
+
title = ""
|
|
472
|
+
for el in iter_elements(root):
|
|
473
|
+
if el.tag == "title":
|
|
474
|
+
title = get_text(el)
|
|
475
|
+
break
|
|
476
|
+
body = root
|
|
477
|
+
for el in iter_elements(root):
|
|
478
|
+
if el.tag == "body":
|
|
479
|
+
body = el
|
|
480
|
+
break
|
|
481
|
+
blocks = _render_blocks(body, base_url)
|
|
482
|
+
if title:
|
|
483
|
+
blocks.insert(0, "# " + title)
|
|
484
|
+
# 压缩 3 连以上空行
|
|
485
|
+
md = "\n\n".join(blocks)
|
|
486
|
+
md = re.sub(r"\n{3,}", "\n\n", md)
|
|
487
|
+
return md.strip()
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
# ============================================================================
|
|
491
|
+
# 四、抓取调度:重试 + UA + robots.txt(对齐上游核心编排,砍掉缓存/代理)
|
|
492
|
+
# ============================================================================
|
|
493
|
+
|
|
494
|
+
_robots_cache = {}
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def robots_allows(url, ua=UA, timeout=8):
|
|
498
|
+
"""robots.txt 检查。robots 拿不到(404/网络错误)时放行——与上游一致。"""
|
|
499
|
+
parsed = urllib.parse.urlsplit(url)
|
|
500
|
+
origin = "%s://%s" % (parsed.scheme, parsed.netloc)
|
|
501
|
+
if origin in _robots_cache:
|
|
502
|
+
return _robots_cache[origin]
|
|
503
|
+
allowed = True
|
|
504
|
+
rp = urllib.robotparser.RobotFileParser()
|
|
505
|
+
rp.set_url(origin + "/robots.txt")
|
|
506
|
+
try:
|
|
507
|
+
req = urllib.request.Request(origin + "/robots.txt", headers={"User-Agent": ua})
|
|
508
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
509
|
+
if resp.status == 200:
|
|
510
|
+
rp.parse(resp.read().decode("utf-8", errors="replace"))
|
|
511
|
+
allowed = rp.can_fetch(ua, url)
|
|
512
|
+
# 非 200(404 等)视为无限制
|
|
513
|
+
except Exception:
|
|
514
|
+
allowed = True # 拿不到 robots 不阻塞抓取
|
|
515
|
+
_robots_cache[origin] = allowed
|
|
516
|
+
return allowed
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def fetch(url, timeout=20, retries=2, check_robots=True, ua=UA):
|
|
520
|
+
"""抓取网页 → (html, final_url)。带指数退避重试。"""
|
|
521
|
+
if check_robots and not robots_allows(url, ua=ua):
|
|
522
|
+
raise PermissionError("robots.txt 不允许抓取: %s" % url)
|
|
523
|
+
last_err = None
|
|
524
|
+
for attempt in range(retries + 1):
|
|
525
|
+
try:
|
|
526
|
+
req = urllib.request.Request(
|
|
527
|
+
url, headers={"User-Agent": ua, "Accept": "text/html,application/xhtml+xml"}
|
|
528
|
+
)
|
|
529
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
530
|
+
raw = resp.read()
|
|
531
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
532
|
+
m = re.search(r"charset=([\w-]+)", ctype)
|
|
533
|
+
charset = m.group(1) if m else "utf-8"
|
|
534
|
+
try:
|
|
535
|
+
html = raw.decode(charset, errors="replace")
|
|
536
|
+
except LookupError:
|
|
537
|
+
html = raw.decode("utf-8", errors="replace")
|
|
538
|
+
return html, resp.geturl()
|
|
539
|
+
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError) as e:
|
|
540
|
+
last_err = e
|
|
541
|
+
if attempt < retries:
|
|
542
|
+
time.sleep(0.8 * (attempt + 1)) # 退避重试
|
|
543
|
+
raise last_err
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ============================================================================
|
|
547
|
+
# 五、结构化提取:JsonCss 风格 schema → JSON(无需 LLM)
|
|
548
|
+
# ============================================================================
|
|
549
|
+
|
|
550
|
+
def extract(html, schema, base_url=""):
|
|
551
|
+
"""
|
|
552
|
+
schema 形如(对齐上游 JsonCss 约定,字段名两种风格都收):
|
|
553
|
+
{
|
|
554
|
+
"baseSelector": "div.item", # 或 base_selector
|
|
555
|
+
"fields": [
|
|
556
|
+
{"name": "title", "selector": "h2", "type": "text"},
|
|
557
|
+
{"name": "url", "selector": "a", "type": "attribute", "attribute": "href"},
|
|
558
|
+
{"name": "raw", "type": "html"}
|
|
559
|
+
]
|
|
560
|
+
}
|
|
561
|
+
返回 list[dict]。
|
|
562
|
+
"""
|
|
563
|
+
root = parse_html(html)
|
|
564
|
+
base_sel = schema.get("baseSelector") or schema.get("base_selector")
|
|
565
|
+
fields = schema.get("fields", [])
|
|
566
|
+
results = []
|
|
567
|
+
bases = select(root, base_sel) if base_sel else [root]
|
|
568
|
+
for base in bases:
|
|
569
|
+
item = {}
|
|
570
|
+
for f in fields:
|
|
571
|
+
name = f.get("name")
|
|
572
|
+
sel = f.get("selector")
|
|
573
|
+
ftype = f.get("type", "text")
|
|
574
|
+
nodes = select(base, sel) if sel else [base]
|
|
575
|
+
if not nodes:
|
|
576
|
+
item[name] = None
|
|
577
|
+
continue
|
|
578
|
+
n = nodes[0]
|
|
579
|
+
if ftype == "text":
|
|
580
|
+
item[name] = get_text(n) or None
|
|
581
|
+
elif ftype == "attribute":
|
|
582
|
+
attr = f.get("attribute", "")
|
|
583
|
+
v = n.get(attr)
|
|
584
|
+
item[name] = urllib.parse.urljoin(base_url, v) if (attr == "href" or attr == "src") and v else v
|
|
585
|
+
elif ftype == "html":
|
|
586
|
+
item[name] = "".join(serialize(c) for c in n.children)
|
|
587
|
+
else:
|
|
588
|
+
item[name] = None
|
|
589
|
+
results.append(item)
|
|
590
|
+
return results
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
# ============================================================================
|
|
594
|
+
# 六、CLI
|
|
595
|
+
# ============================================================================
|
|
596
|
+
|
|
597
|
+
def main(argv=None):
|
|
598
|
+
parser = argparse.ArgumentParser(
|
|
599
|
+
description="pialuo —— 轻量网页抓取与内容提炼(爬罗剔抉,刮垢磨光)"
|
|
600
|
+
)
|
|
601
|
+
parser.add_argument("url", help="目标网页 URL")
|
|
602
|
+
parser.add_argument("--schema", help="JsonCss 风格 schema JSON 文件路径")
|
|
603
|
+
parser.add_argument("--out", help="输出文件路径(默认打印到 stdout)")
|
|
604
|
+
parser.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
605
|
+
parser.add_argument("--timeout", type=int, default=20, help="单次请求超时秒数")
|
|
606
|
+
parser.add_argument("--retries", type=int, default=2, help="失败重试次数")
|
|
607
|
+
parser.add_argument("--no-robots", action="store_true", help="跳过 robots.txt 检查")
|
|
608
|
+
parser.add_argument("--word-threshold", type=int, default=10,
|
|
609
|
+
help="文本密度剪枝阈值(词数:拉丁文按词、中文按字),默认 10")
|
|
610
|
+
parser.add_argument("--profile", action="store_true",
|
|
611
|
+
help="输出耗时与内存峰值(tracemalloc)")
|
|
612
|
+
args = parser.parse_args(argv)
|
|
613
|
+
|
|
614
|
+
t0 = time.perf_counter()
|
|
615
|
+
if args.profile:
|
|
616
|
+
import tracemalloc
|
|
617
|
+
tracemalloc.start()
|
|
618
|
+
|
|
619
|
+
try:
|
|
620
|
+
html, final_url = fetch(args.url, timeout=args.timeout,
|
|
621
|
+
retries=args.retries, check_robots=not args.no_robots)
|
|
622
|
+
except PermissionError as e:
|
|
623
|
+
print("错误: %s" % e, file=sys.stderr)
|
|
624
|
+
return 3
|
|
625
|
+
except Exception as e:
|
|
626
|
+
print("抓取失败: %s" % e, file=sys.stderr)
|
|
627
|
+
return 1
|
|
628
|
+
|
|
629
|
+
t_fetch = time.perf_counter() - t0
|
|
630
|
+
|
|
631
|
+
if args.schema:
|
|
632
|
+
with open(args.schema, "r", encoding="utf-8") as f:
|
|
633
|
+
schema = json.load(f)
|
|
634
|
+
data = extract(html, schema, base_url=final_url)
|
|
635
|
+
output = json.dumps(data, ensure_ascii=False, indent=2)
|
|
636
|
+
else:
|
|
637
|
+
root = parse_html(html)
|
|
638
|
+
prune_tree(root, word_count_threshold=args.word_threshold)
|
|
639
|
+
output = to_markdown(root, base_url=final_url)
|
|
640
|
+
if args.json:
|
|
641
|
+
output = json.dumps({"url": final_url, "markdown": output},
|
|
642
|
+
ensure_ascii=False, indent=2)
|
|
643
|
+
|
|
644
|
+
t_total = time.perf_counter() - t0
|
|
645
|
+
|
|
646
|
+
if args.profile:
|
|
647
|
+
current, peak = tracemalloc.get_traced_memory()
|
|
648
|
+
print("[profile] 抓取耗时 %.2fs | 总耗时 %.2fs | 内存峰值 %.1f MB"
|
|
649
|
+
% (t_fetch, t_total, peak / 1024 / 1024), file=sys.stderr)
|
|
650
|
+
|
|
651
|
+
if args.out:
|
|
652
|
+
with open(args.out, "w", encoding="utf-8") as f:
|
|
653
|
+
f.write(output)
|
|
654
|
+
print("已写入 %s(%d 字符,抓取 %.2fs,总耗时 %.2fs)"
|
|
655
|
+
% (args.out, len(output), t_fetch, t_total), file=sys.stderr)
|
|
656
|
+
else:
|
|
657
|
+
try:
|
|
658
|
+
print(output)
|
|
659
|
+
except BrokenPipeError:
|
|
660
|
+
# 下游管道提前关闭(如 head)时安静退出
|
|
661
|
+
pass
|
|
662
|
+
return 0
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
if __name__ == "__main__":
|
|
666
|
+
sys.exit(main())
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""pialuo MCP 服务:JSON-RPC 2.0 over stdio(零依赖,照道统算子谱模式)。
|
|
4
|
+
|
|
5
|
+
启动:python3 mcp_server.py
|
|
6
|
+
工具:
|
|
7
|
+
fetch_page(url) —— 抓取网页并清洗为 LLM 友好的 Markdown;
|
|
8
|
+
extract_structured(url, schema) —— 按 JsonCss 风格 schema 做结构化提取。
|
|
9
|
+
|
|
10
|
+
无凭据依赖:本服务不读取、不存储任何密钥。
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
from . import core as pialuo # noqa: F401
|
|
19
|
+
|
|
20
|
+
TOOLS_META = {
|
|
21
|
+
"fetch_page": {
|
|
22
|
+
"desc": "爬罗抓取:抓取公开网页,文本密度剪枝清洗后输出 LLM 友好的 Markdown。纯静态解析,动态渲染页拿不到正文(边界如实)。",
|
|
23
|
+
"schema": {"type": "object",
|
|
24
|
+
"properties": {
|
|
25
|
+
"url": {"type": "string", "description": "目标网页 URL"},
|
|
26
|
+
"timeout": {"type": "integer", "description": "单次请求超时秒数,默认 20"},
|
|
27
|
+
"retries": {"type": "integer", "description": "失败重试次数,默认 2"},
|
|
28
|
+
"word_threshold": {"type": "integer", "description": "文本密度剪枝阈值,默认 10"}},
|
|
29
|
+
"required": ["url"]},
|
|
30
|
+
},
|
|
31
|
+
"extract_structured": {
|
|
32
|
+
"desc": "剔抉提取:按 JsonCss 风格 schema(baseSelector + fields 列表,字段含 name/selector/type/attribute)对网页做结构化提取,无需 LLM。",
|
|
33
|
+
"schema": {"type": "object",
|
|
34
|
+
"properties": {
|
|
35
|
+
"url": {"type": "string", "description": "目标网页 URL"},
|
|
36
|
+
"schema": {"type": "object", "description": "JsonCss 风格提取 schema"}},
|
|
37
|
+
"required": ["url", "schema"]},
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def tool_fetch_page(args: dict) -> dict:
|
|
43
|
+
url = str(args.get("url", "")).strip()
|
|
44
|
+
if not url:
|
|
45
|
+
return {"ok": False, "error": "url required"}
|
|
46
|
+
html, final_url = pialuo.fetch(
|
|
47
|
+
url, timeout=int(args.get("timeout", 20)),
|
|
48
|
+
retries=int(args.get("retries", 2)), check_robots=True)
|
|
49
|
+
root = pialuo.parse_html(html)
|
|
50
|
+
pialuo.prune_tree(root, word_count_threshold=int(args.get("word_threshold", 10)))
|
|
51
|
+
markdown = pialuo.to_markdown(root, base_url=final_url)
|
|
52
|
+
return {"ok": True, "url": final_url, "markdown": markdown}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def tool_extract_structured(args: dict) -> dict:
|
|
56
|
+
url = str(args.get("url", "")).strip()
|
|
57
|
+
schema = args.get("schema")
|
|
58
|
+
if not url or not isinstance(schema, dict):
|
|
59
|
+
return {"ok": False, "error": "url and schema(object) required"}
|
|
60
|
+
html, final_url = pialuo.fetch(url, timeout=20, retries=2, check_robots=True)
|
|
61
|
+
data = pialuo.extract(html, schema, base_url=final_url)
|
|
62
|
+
return {"ok": True, "url": final_url, "data": data}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
DISPATCH = {"fetch_page": tool_fetch_page, "extract_structured": tool_extract_structured}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def handle(req: dict) -> dict | None:
|
|
69
|
+
method, rid = req.get("method"), req.get("id")
|
|
70
|
+
if method == "initialize":
|
|
71
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {
|
|
72
|
+
"protocolVersion": "2024-11-05",
|
|
73
|
+
"capabilities": {"tools": {}},
|
|
74
|
+
"serverInfo": {"name": "pialuo", "version": "0.1.0"}}}
|
|
75
|
+
if method == "tools/list":
|
|
76
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {
|
|
77
|
+
"tools": [{"name": n, "description": m["desc"], "inputSchema": m["schema"]}
|
|
78
|
+
for n, m in TOOLS_META.items()]}}
|
|
79
|
+
if method == "tools/call":
|
|
80
|
+
params = req.get("params") or {}
|
|
81
|
+
name = params.get("name")
|
|
82
|
+
try:
|
|
83
|
+
out = DISPATCH[name](params.get("args") or {})
|
|
84
|
+
text = out.get("markdown") or json.dumps(out.get("data"), ensure_ascii=False) \
|
|
85
|
+
if out.get("ok") else json.dumps(out, ensure_ascii=False)
|
|
86
|
+
if out.get("ok") and name == "extract_structured":
|
|
87
|
+
text = json.dumps(out["data"], ensure_ascii=False, indent=2)
|
|
88
|
+
except PermissionError as exc:
|
|
89
|
+
text = f"robots 拒绝: {exc}"
|
|
90
|
+
except Exception as exc: # 工具内异常转文本,不中断服务
|
|
91
|
+
text = f"{name} failed: {exc}"
|
|
92
|
+
return {"jsonrpc": "2.0", "id": rid, "result": {
|
|
93
|
+
"content": [{"type": "text", "text": text}]}}
|
|
94
|
+
if method == "notifications/initialized":
|
|
95
|
+
return None
|
|
96
|
+
if rid is not None:
|
|
97
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "method not found"}}
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main() -> None:
|
|
102
|
+
for line in sys.stdin:
|
|
103
|
+
line = line.strip()
|
|
104
|
+
if not line:
|
|
105
|
+
continue
|
|
106
|
+
try:
|
|
107
|
+
req = json.loads(line)
|
|
108
|
+
except json.JSONDecodeError:
|
|
109
|
+
continue
|
|
110
|
+
resp = handle(req)
|
|
111
|
+
if resp is not None:
|
|
112
|
+
print(json.dumps(resp, ensure_ascii=False), flush=True)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__ == "__main__":
|
|
116
|
+
main()
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pialuo
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 爬罗剔抉 pialuo — 轻量网页抓取与结构化提取算子:纯标准库零依赖,内存个位数 MB(提炼自 Crawl4AI 核心思路)
|
|
5
|
+
Author: tanbopiao
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://gitcode.com/zongyuangen/pialuo
|
|
8
|
+
Project-URL: Repository, https://github.com/tanbopiao/pialuo
|
|
9
|
+
Keywords: crawler,web-scraping,llm,mcp,extractor,yuanshu
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
19
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pialuo —— 爬罗剔抉,刮垢磨光
|
|
26
|
+
|
|
27
|
+
轻量化网页抓取与内容提炼算子。抓取网页、按文本密度剪枝去噪,输出 LLM 友好的
|
|
28
|
+
Markdown 或按 CSS 选择器 schema 提取结构化 JSON。
|
|
29
|
+
|
|
30
|
+
> 名字取自韩愈《进学解》:"爬罗剔抉,刮垢磨光"——爬罗(搜集)剔抉(挑选),
|
|
31
|
+
> 正是"抓取→清洗→提炼"这件事。
|
|
32
|
+
|
|
33
|
+
纯 Python 标准库实现,零第三方依赖,单文件 666 行。
|
|
34
|
+
|
|
35
|
+
## 用法
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
# 抓取并输出清洗后的 Markdown
|
|
39
|
+
python pialuo.py https://www.python.org/
|
|
40
|
+
|
|
41
|
+
# 输出到文件,显示耗时与内存
|
|
42
|
+
python pialuo.py https://www.python.org/ --out page.md --profile
|
|
43
|
+
|
|
44
|
+
# 按 schema 提取结构化 JSON(无需 LLM)
|
|
45
|
+
python pialuo.py https://www.python.org/ --schema schema.json
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
schema 格式(JsonCss 风格):
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"baseSelector": "ul.menu li",
|
|
53
|
+
"fields": [
|
|
54
|
+
{"name": "title", "selector": "a", "type": "text"},
|
|
55
|
+
{"name": "url", "selector": "a", "type": "attribute", "attribute": "href"}
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
选择器支持子集:`tag`、`.class`、`#id`、后代空格组合。
|
|
61
|
+
|
|
62
|
+
## MCP 服务
|
|
63
|
+
|
|
64
|
+
仓库内 `mcp_server.py` 提供 JSON-RPC 2.0 over stdio 的 MCP 服务(零依赖),
|
|
65
|
+
任何支持 MCP 的客户端可直接接入:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
python mcp_server.py
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
工具:
|
|
72
|
+
- `fetch_page(url, timeout?, retries?, word_threshold?)` —— 抓取网页并清洗为 LLM 友好 Markdown;
|
|
73
|
+
- `extract_structured(url, schema)` —— 按 JsonCss 风格 schema 做结构化提取,无需 LLM。
|
|
74
|
+
|
|
75
|
+
## 与 Crawl4AI 的取舍对比
|
|
76
|
+
|
|
77
|
+
| 维度 | Crawl4AI(上游) | pialuo(本算子) |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| 定位 | 全功能 Agent 爬取框架 | 单一算子:抓取→清洗→提取 |
|
|
80
|
+
| 代码形态 | 543 个 py 文件、约 15.6 万行 | 单文件 666 行 |
|
|
81
|
+
| 依赖 | 25+(Playwright、numpy、litellm 等) | 0(纯标准库) |
|
|
82
|
+
| 部署形态 | Docker 镜像 8.2GB,要求 4GB RAM | 一个 py 文件直接跑 |
|
|
83
|
+
| 空闲内存 | 538MB(实测) | 进程 RSS 峰值约 25MB(含解释器基线),解析 51KB 页面 tracemalloc 峰值 0.78MB |
|
|
84
|
+
| 51KB 页面处理耗时 | — | 解析+剪枝+渲染 78ms |
|
|
85
|
+
| 抓取调度 | asyncio 并发/重试/robots/缓存 | 同步抓取/重试/robots(缓存砍掉) |
|
|
86
|
+
| 文本密度剪枝 | PruningContentFilter | 同思路自研:分词噪音匹配 + 词数阈值 + 链接密度 |
|
|
87
|
+
| 结构化提取 | JsonCss/JsonXPath + LLM 策略 | JsonCss 子集(LLM 策略砍掉) |
|
|
88
|
+
| 浏览器/JS 执行 | Playwright/patchright 双栈 | 无——动态渲染页面拿不到正文 |
|
|
89
|
+
| Docker API 服务层 | 1211 行 server.py(上游漏洞聚集地) | 无此层,攻击面不存在 |
|
|
90
|
+
| CLI/Web UI/MCP/PDF/代理/深爬取 | 有 | 全部砍掉 |
|
|
91
|
+
|
|
92
|
+
**功能对齐的核心场景**:静态页抓取 → 去导航/页脚/广告 → LLM 友好 Markdown;
|
|
93
|
+
CSS 选择器 schema → 结构化 JSON。实测 python.org 首页:新闻列表、成功故事、
|
|
94
|
+
PSF 介绍等正文完整保留,导航/横幅/脚本剔除。
|
|
95
|
+
|
|
96
|
+
**如实边界**:需要 JS 渲染的页面(如 Bing 首页搜索结果)拿不到正文;
|
|
97
|
+
无浏览器、无 JS 执行、无并发调度、无缓存、无代理轮换。
|
|
98
|
+
|
|
99
|
+
## 理念致谢
|
|
100
|
+
|
|
101
|
+
本项目功能、架构与逻辑思路致谢 [Crawl4AI](https://github.com/unclecode/crawl4ai)
|
|
102
|
+
(Apache-2.0)。本仓库为**独立重写,无任何上游代码血缘**;依 Crawl4AI 许可证之
|
|
103
|
+
Attribution Requirement,公开分发时注明出处如上。
|
|
104
|
+
|
|
105
|
+
## 复刻哲学
|
|
106
|
+
|
|
107
|
+
外来佳作功能、架构、逻辑皆可复刻,算子代码必自研完善;收编先深扫,复刻必致谢,轻量一个量级。
|
|
108
|
+
|
|
109
|
+
## 许可证
|
|
110
|
+
|
|
111
|
+
MIT(见 LICENSE)。
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
pialuo/__init__.py
|
|
5
|
+
pialuo/__main__.py
|
|
6
|
+
pialuo/core.py
|
|
7
|
+
pialuo/mcp.py
|
|
8
|
+
pialuo.egg-info/PKG-INFO
|
|
9
|
+
pialuo.egg-info/SOURCES.txt
|
|
10
|
+
pialuo.egg-info/dependency_links.txt
|
|
11
|
+
pialuo.egg-info/entry_points.txt
|
|
12
|
+
pialuo.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pialuo
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pialuo"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "爬罗剔抉 pialuo — 轻量网页抓取与结构化提取算子:纯标准库零依赖,内存个位数 MB(提炼自 Crawl4AI 核心思路)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "tanbopiao" }]
|
|
13
|
+
keywords = ["crawler", "web-scraping", "llm", "mcp", "extractor", "yuanshu"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
|
|
24
|
+
"Topic :: Text Processing :: Markup :: HTML",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://gitcode.com/zongyuangen/pialuo"
|
|
29
|
+
Repository = "https://github.com/tanbopiao/pialuo"
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
pialuo = "pialuo.core:main"
|
|
33
|
+
pialuo-mcp = "pialuo.mcp:main"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools]
|
|
36
|
+
packages = ["pialuo"]
|
pialuo-0.1.0/setup.cfg
ADDED