argo-search 2.9.9 → 2.10.0
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.
- package/README.en.md +24 -21
- package/README.es.md +24 -21
- package/README.ja.md +23 -20
- package/README.ko.md +23 -20
- package/README.md +26 -21
- package/SKILL.md +5 -5
- package/backends/domain_profiles.json +76 -0
- package/backends/engine_registry.yaml +161 -5
- package/backends/quota_profiles.json +122 -2
- package/bin/argo +22 -1
- package/bin/argo.js +3 -3
- package/config.yaml +128 -21
- package/docs/ARGO_INTRO.md +4 -4
- package/docs/ENGINE_CATALOG.md +64 -44
- package/docs/MCP_SETUP.md +1 -1
- package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
- package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
- package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
- package/engines/specs/clawhub.yaml +16 -15
- package/engines/specs/deepseek1024.yaml +46 -0
- package/engines/specs/dsh_hub.yaml +44 -0
- package/engines/specs/dshopen.yaml +32 -0
- package/engines/specs/explainx.yaml +32 -0
- package/engines/specs/gbfs_nyc.yaml +6 -1
- package/engines/specs/metaso_doc.yaml +49 -0
- package/engines/specs/metaso_image.yaml +65 -0
- package/engines/specs/metaso_podcast.yaml +60 -0
- package/engines/specs/metaso_scholar.yaml +57 -0
- package/engines/specs/metaso_video.yaml +62 -0
- package/engines/specs/ncpssd.yaml +41 -0
- package/engines/specs/sciverse.yaml +72 -0
- package/engines/specs/skills_sh.yaml +32 -0
- package/engines/specs/skillsmp.yaml +18 -16
- package/package.json +3 -2
- package/packages/dsh-plugin/README.md +3 -2
- package/packages/dsh-plugin/package.json +1 -1
- package/packages/dsh-plugin/test/size-gate.test.js +113 -0
- package/scripts/adaptive.py +41 -14
- package/scripts/article.py +6 -1
- package/scripts/article_meta.py +151 -2
- package/scripts/bench_general_pool.py +145 -0
- package/scripts/candidate_envelope.py +45 -4
- package/scripts/charset_decode.py +127 -0
- package/scripts/crawl.py +240 -74
- package/scripts/crawl_frontier.py +217 -0
- package/scripts/crawl_policy.py +174 -0
- package/scripts/engine_dispatch.py +22 -15
- package/scripts/engine_failure.py +15 -0
- package/scripts/engine_validate.py +8 -0
- package/scripts/engines.py +10 -0
- package/scripts/engines_base.py +12 -0
- package/scripts/engines_builders.py +14 -0
- package/scripts/engines_builders_dsh.py +330 -0
- package/scripts/engines_builders_skill.py +314 -0
- package/scripts/fetch_v3.py +37 -5
- package/scripts/gen_engine_catalog.py +218 -2
- package/scripts/general_pool.py +162 -0
- package/scripts/http_client.py +38 -42
- package/scripts/image_ops.py +4 -0
- package/scripts/install.ps1 +47 -19
- package/scripts/install.sh +45 -20
- package/scripts/matrix_search_eval.py +17 -1
- package/scripts/mcp_transport.py +1 -1
- package/scripts/ncpssd_bridge.py +123 -0
- package/scripts/paid_policy.py +109 -13
- package/scripts/pre-commit +19 -4
- package/scripts/query_signals.py +156 -3
- package/scripts/redskill/redskill_engine.py +29 -2
- package/scripts/release_check.py +209 -0
- package/scripts/retry_policy.py +22 -1
- package/scripts/robots_guard.py +26 -0
- package/scripts/route.py +11 -8
- package/scripts/route_cache.py +6 -0
- package/scripts/route_combo.py +37 -59
- package/scripts/route_domains.py +4 -1
- package/scripts/route_policy.py +6 -0
- package/scripts/search.py +9 -1
- package/scripts/search_cli.py +27 -0
- package/scripts/search_entry.py +9 -0
- package/scripts/search_output.py +29 -0
- package/scripts/search_pipeline.py +39 -1
- package/scripts/search_rank.py +1 -0
- package/scripts/social_engines/bilibili_engine.py +163 -26
- package/scripts/social_engines/reddit_engine.py +52 -51
- package/scripts/source_selection.py +302 -0
- package/scripts/video_fetch.py +303 -0
- package/scripts/video_meta.py +225 -0
- package/scripts/video_route.py +65 -0
- package/scripts/watch.py +123 -0
- package/scripts/local_engines.py +0 -321
package/scripts/crawl.py
CHANGED
|
@@ -1,13 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""crawl.py — 站点级爬取(fetch_v3 降级链:增强 HTTP → TLS 指纹 → Wayback
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
"""crawl.py — 站点级爬取(fetch_v3 降级链:增强 HTTP → TLS 指纹 → Wayback)。
|
|
3
|
+
|
|
4
|
+
与旧版的区别在「抓什么」和「怎么给」两处:
|
|
5
|
+
|
|
6
|
+
抓什么:URL 先过 crawl_frontier(归一化、资产过滤、坏路径、范围),正文哈希去重;
|
|
7
|
+
每次请求过 crawl_policy(每主机间隔/并发、429 退避),robots 合规仍由
|
|
8
|
+
fetch_v3 内部的 robots_guard 负责。
|
|
9
|
+
怎么给:默认每页正文按 --max-chars 截断,--query 用现成的 BM25 聚焦只回相关段落,
|
|
10
|
+
--full 回全文。旧版固定 content[:500]、每页只跟进前 5 个链接,这两处
|
|
11
|
+
是「抓到了但没法用」的主因。
|
|
12
|
+
|
|
13
|
+
批量场景禁浏览器降级:BFS 可能爬几十页,每页启动 Chrome CDP 会拖慢整体。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import re
|
|
20
|
+
import time
|
|
21
|
+
from collections import deque
|
|
22
|
+
|
|
23
|
+
from bounded_run import TaskError, run_bounded
|
|
6
24
|
from cli_io import dumps
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
25
|
+
from crawl_frontier import (
|
|
26
|
+
Frontier,
|
|
27
|
+
canonical,
|
|
28
|
+
extract_links,
|
|
29
|
+
looks_html,
|
|
30
|
+
strip_session_params,
|
|
31
|
+
)
|
|
32
|
+
from crawl_policy import HostGate, retry_after_seconds, status_of
|
|
33
|
+
|
|
34
|
+
# 单页抓取额度:需要完整 HTML 才能提取全部链接。fetch_v3 的 html 交付视图是
|
|
35
|
+
# max_chars*2,旧版用 2000 当抓取额度等于只看前 4KB,正文中后段的链接全丢。
|
|
36
|
+
_FETCH_CHARS = 200000
|
|
37
|
+
_PER_PAGE_LINKS = 200
|
|
38
|
+
_DEFAULT_MAX_CHARS = 2000
|
|
11
39
|
|
|
12
40
|
|
|
13
41
|
def _crawl_fetch(url: str, max_chars: int, timeout: int, raw: bool = True) -> dict:
|
|
@@ -17,85 +45,218 @@ def _crawl_fetch(url: str, max_chars: int, timeout: int, raw: bool = True) -> di
|
|
|
17
45
|
必须绕过缓存才能拿到完整页面。通过模块级 fetch_page 转发,
|
|
18
46
|
测试可 monkeypatch crawl.fetch_page 注入假抓取。
|
|
19
47
|
"""
|
|
20
|
-
|
|
48
|
+
from fetch_v3 import fetch_v3
|
|
49
|
+
return fetch_v3(url, max_chars=max_chars, timeout=float(timeout),
|
|
50
|
+
use_browser_fallback=False, skip_cache=raw, need_html=raw)
|
|
21
51
|
|
|
22
52
|
|
|
23
|
-
# 默认实现指向 fetch_v3
|
|
24
|
-
|
|
53
|
+
# 默认实现指向 fetch_v3 的兼容入口;测试可整体替换 fetch_page,
|
|
54
|
+
# 也可以按旧契约替换 _crawl_fetch(这里保留一层转发,两种打桩都生效)。
|
|
55
|
+
def fetch_page(url: str, max_chars: int, timeout: int, raw: bool = True) -> dict:
|
|
56
|
+
return _crawl_fetch(url, max_chars, timeout, raw=raw)
|
|
25
57
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
58
|
+
|
|
59
|
+
def _content_hash(text: str) -> str:
|
|
60
|
+
norm = re.sub(r"\s+", " ", text or "").strip()
|
|
61
|
+
return hashlib.sha256(norm.encode("utf-8")).hexdigest()[:16]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _focus(content: str, query: str) -> str:
|
|
65
|
+
if not query or not content:
|
|
66
|
+
return content
|
|
67
|
+
try:
|
|
68
|
+
from focus_extract import focus_extract
|
|
69
|
+
return focus_extract(content, query, top_k=5)
|
|
70
|
+
except Exception:
|
|
71
|
+
return content
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _shape_page(result: dict, url: str, depth: int, max_chars: int,
|
|
75
|
+
query: str) -> dict | None:
|
|
76
|
+
content = result.get("content") or ""
|
|
77
|
+
if not content:
|
|
78
|
+
return None
|
|
79
|
+
focused = _focus(content, query)
|
|
80
|
+
delivered = focused if max_chars <= 0 else focused[:max_chars]
|
|
81
|
+
return {
|
|
82
|
+
"url": url,
|
|
83
|
+
"depth": depth,
|
|
84
|
+
"title": str(result.get("title") or "")[:200],
|
|
85
|
+
"content": delivered,
|
|
86
|
+
"length": len(focused),
|
|
87
|
+
"hash": _content_hash(content),
|
|
88
|
+
"status": status_of(result),
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _fetch_batch(batch: list[tuple[str, int]], timeout: int, gate: HostGate,
|
|
93
|
+
stats: dict) -> list[tuple[str, int, dict]]:
|
|
94
|
+
"""并发抓一层;gate 在 worker 内部阻塞,所以等待预算要算上排队时间。"""
|
|
95
|
+
interval = gate.interval
|
|
96
|
+
|
|
97
|
+
def worker(item: tuple[str, int]) -> dict:
|
|
98
|
+
url, _depth = item
|
|
99
|
+
with gate.slot(url) as lease:
|
|
100
|
+
try:
|
|
101
|
+
result = fetch_page(url, _FETCH_CHARS, timeout, raw=True)
|
|
102
|
+
except Exception as exc: # noqa: BLE001 - 单页失败不拖垮整次爬取
|
|
103
|
+
lease.note(0)
|
|
104
|
+
stats["fetch_failed"] += 1
|
|
105
|
+
return {"success": False, "error": str(exc)[:160]}
|
|
106
|
+
lease.note(status_of(result), retry_after_seconds(result))
|
|
107
|
+
return result
|
|
108
|
+
|
|
109
|
+
finished, unfinished = run_bounded(
|
|
110
|
+
batch, worker,
|
|
111
|
+
wait_s=float(timeout) * 2 + interval * max(1, len(batch)) + 5,
|
|
112
|
+
max_workers=min(len(batch), 8),
|
|
113
|
+
)
|
|
114
|
+
stats["unfinished_urls"] += len(unfinished)
|
|
115
|
+
out = []
|
|
116
|
+
for (url, depth), result in finished:
|
|
117
|
+
if isinstance(result, TaskError) or not isinstance(result, dict):
|
|
118
|
+
stats["fetch_failed"] += 1
|
|
53
119
|
continue
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
120
|
+
out.append((url, depth, result))
|
|
121
|
+
# 按入队顺序返回,不按线程完成先后:同一份输入两次爬取要得到同样的页序,
|
|
122
|
+
# 否则测试和调用方的 diff 都会被调度抖动影响。
|
|
123
|
+
order = {url: index for index, (url, _depth) in enumerate(batch)}
|
|
124
|
+
out.sort(key=lambda item: order.get(item[0], len(order)))
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _crawl(url: str, max_pages: int, max_depth: int, timeout: int,
|
|
129
|
+
strategy: str, query: str = "", scope: str = "auto",
|
|
130
|
+
max_chars: int = _DEFAULT_MAX_CHARS, interval: float = 1.0,
|
|
131
|
+
policy: HostGate | None = None) -> dict:
|
|
132
|
+
t0 = time.monotonic()
|
|
133
|
+
frontier = Frontier(url, scope=scope)
|
|
134
|
+
gate = policy or HostGate(interval=interval)
|
|
135
|
+
stats = {key: 0 for key in (
|
|
136
|
+
"offsite", "asset", "pathological", "out_of_scope", "non_html",
|
|
137
|
+
"duplicate", "fetch_failed", "unfinished_urls")}
|
|
138
|
+
pages: list[dict] = []
|
|
139
|
+
seen_hashes: set[str] = set()
|
|
140
|
+
visited: set[str] = set()
|
|
141
|
+
|
|
142
|
+
if strategy == "sitemap":
|
|
143
|
+
seeds = _sitemap_seeds(url, timeout, gate, stats)
|
|
144
|
+
queue = deque((seed, 0) for seed in seeds[:max_pages * 2])
|
|
145
|
+
else:
|
|
146
|
+
queue = deque([(strip_session_params(canonical(url)), 0)])
|
|
147
|
+
|
|
63
148
|
while queue and len(pages) < max_pages:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
149
|
+
batch: list[tuple[str, int]] = []
|
|
150
|
+
while queue and len(batch) < max_pages - len(pages):
|
|
151
|
+
candidate, depth = queue.popleft()
|
|
152
|
+
if depth > max_depth:
|
|
153
|
+
continue
|
|
154
|
+
ok, reason = frontier.accept(candidate)
|
|
155
|
+
if not ok:
|
|
156
|
+
stats[reason] += 1
|
|
69
157
|
continue
|
|
70
|
-
visited
|
|
71
|
-
|
|
72
|
-
|
|
158
|
+
if candidate in visited:
|
|
159
|
+
continue
|
|
160
|
+
visited.add(candidate)
|
|
161
|
+
batch.append((candidate, depth))
|
|
162
|
+
if not batch:
|
|
73
163
|
break
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if
|
|
164
|
+
for candidate, depth, result in _fetch_batch(batch, timeout, gate, stats):
|
|
165
|
+
if not result.get("success"):
|
|
166
|
+
stats["fetch_failed"] += 1
|
|
167
|
+
continue
|
|
168
|
+
html = result.get("html") or ""
|
|
169
|
+
if html and not looks_html(html):
|
|
170
|
+
stats["non_html"] += 1
|
|
80
171
|
continue
|
|
81
|
-
|
|
172
|
+
page = _shape_page(result, candidate, depth, max_chars, query)
|
|
173
|
+
if page is None:
|
|
174
|
+
stats["non_html"] += 1
|
|
175
|
+
continue
|
|
176
|
+
if page["hash"] in seen_hashes:
|
|
177
|
+
stats["duplicate"] += 1
|
|
178
|
+
else:
|
|
179
|
+
seen_hashes.add(page["hash"])
|
|
180
|
+
pages.append(page)
|
|
82
181
|
if len(pages) >= max_pages:
|
|
83
182
|
break
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
queue.append((
|
|
91
|
-
return {
|
|
92
|
-
|
|
183
|
+
if depth >= max_depth:
|
|
184
|
+
continue
|
|
185
|
+
# 正文重复的页面仍要跟进链接:列表页/分页常常正文相同但链接不同。
|
|
186
|
+
for link in extract_links(html, candidate)[:_PER_PAGE_LINKS]:
|
|
187
|
+
link = strip_session_params(link)
|
|
188
|
+
if link not in visited:
|
|
189
|
+
queue.append((link, depth + 1))
|
|
190
|
+
return {
|
|
191
|
+
"url": url,
|
|
192
|
+
"pages": pages,
|
|
193
|
+
"total": len(pages),
|
|
194
|
+
"skipped": stats,
|
|
195
|
+
"elapsed_ms": int((time.monotonic() - t0) * 1000),
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _sitemap_seeds(url: str, timeout: int, gate: HostGate, stats: dict) -> list[str]:
|
|
200
|
+
"""取 sitemap 里的 <loc>,过前沿规则后返回;取不到退回空列表。"""
|
|
201
|
+
sitemap_url = url.rstrip("/") + "/sitemap.xml"
|
|
202
|
+
try:
|
|
203
|
+
with gate.slot(sitemap_url) as lease:
|
|
204
|
+
result = fetch_page(sitemap_url, _FETCH_CHARS, timeout, raw=True)
|
|
205
|
+
lease.note(status_of(result), retry_after_seconds(result))
|
|
206
|
+
except Exception:
|
|
207
|
+
return []
|
|
208
|
+
if not result.get("success"):
|
|
209
|
+
return []
|
|
210
|
+
text = result.get("html") or ""
|
|
211
|
+
locs = re.findall(r"<loc>\s*(.*?)\s*</loc>", text, flags=re.IGNORECASE | re.DOTALL)
|
|
212
|
+
# sitemap 天然列全站,范围按整个主机算,不套起始路径前缀。
|
|
213
|
+
frontier = Frontier(url, scope="domain")
|
|
214
|
+
seeds = []
|
|
215
|
+
for loc in locs:
|
|
216
|
+
loc = strip_session_params(canonical(loc))
|
|
217
|
+
ok, reason = frontier.accept(loc)
|
|
218
|
+
if not ok:
|
|
219
|
+
stats[reason] += 1
|
|
220
|
+
continue
|
|
221
|
+
seeds.append(loc)
|
|
222
|
+
return seeds
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def crawl_sitemap(url: str, max_pages: int = 20, timeout: int = 10,
|
|
226
|
+
query: str = "", scope: str = "auto",
|
|
227
|
+
max_chars: int = _DEFAULT_MAX_CHARS, interval: float = 1.0,
|
|
228
|
+
policy: HostGate | None = None) -> dict:
|
|
229
|
+
return _crawl(url, max_pages, 0, timeout, "sitemap", query=query,
|
|
230
|
+
scope=scope, max_chars=max_chars, interval=interval,
|
|
231
|
+
policy=policy)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def crawl_bfs(url: str, max_pages: int = 10, max_depth: int = 2,
|
|
235
|
+
timeout: int = 8, query: str = "", scope: str = "auto",
|
|
236
|
+
max_chars: int = _DEFAULT_MAX_CHARS, interval: float = 1.0,
|
|
237
|
+
policy: HostGate | None = None) -> dict:
|
|
238
|
+
return _crawl(url, max_pages, max_depth, timeout, "bfs", query=query,
|
|
239
|
+
scope=scope, max_chars=max_chars, interval=interval,
|
|
240
|
+
policy=policy)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
if __name__ == "__main__":
|
|
93
244
|
import argparse
|
|
94
245
|
p = argparse.ArgumentParser()
|
|
95
246
|
p.add_argument('url')
|
|
96
|
-
p.add_argument('--strategy', default='bfs', choices=['sitemap','bfs'])
|
|
247
|
+
p.add_argument('--strategy', default='bfs', choices=['sitemap', 'bfs'])
|
|
97
248
|
p.add_argument('--max-pages', type=int, default=10)
|
|
98
249
|
p.add_argument('--max-depth', type=int, default=2)
|
|
250
|
+
p.add_argument('--query', default='',
|
|
251
|
+
help='BM25 聚焦:每页只回与查询相关的段落')
|
|
252
|
+
p.add_argument('--scope', default='auto',
|
|
253
|
+
choices=['auto', 'path', 'domain'],
|
|
254
|
+
help='auto=起始目录(叶子页上提一层)/ path=严格前缀 / domain=整站')
|
|
255
|
+
p.add_argument('--max-chars', type=int, default=_DEFAULT_MAX_CHARS,
|
|
256
|
+
help='每页交付字符数,0=不截断')
|
|
257
|
+
p.add_argument('--full', action='store_true', help='等价于 --max-chars 0')
|
|
258
|
+
p.add_argument('--interval', type=float, default=1.0,
|
|
259
|
+
help='同一主机两次请求的最小间隔(秒),默认 1')
|
|
99
260
|
# bin/argo 的 usage 承诺了 Common flags「--json」,此前 crawl/extract 的
|
|
100
261
|
# parser 里没有它,Agent 照文档传参直接撞墙(error: unrecognized
|
|
101
262
|
# arguments,exit 2)。这里接住该开关并给出真实语义:默认仍是截断预览
|
|
@@ -104,9 +265,14 @@ if __name__ == '__main__':
|
|
|
104
265
|
p.add_argument('--json', action='store_true',
|
|
105
266
|
help='输出完整 JSON(默认为 2000 字符截断预览)')
|
|
106
267
|
args = p.parse_args()
|
|
268
|
+
max_chars = 0 if args.full else args.max_chars
|
|
107
269
|
if args.strategy == 'sitemap':
|
|
108
|
-
r = crawl_sitemap(args.url, args.max_pages
|
|
270
|
+
r = crawl_sitemap(args.url, args.max_pages, query=args.query,
|
|
271
|
+
scope=args.scope, max_chars=max_chars,
|
|
272
|
+
interval=args.interval)
|
|
109
273
|
else:
|
|
110
|
-
r = crawl_bfs(args.url, args.max_pages, args.max_depth
|
|
274
|
+
r = crawl_bfs(args.url, args.max_pages, args.max_depth,
|
|
275
|
+
query=args.query, scope=args.scope, max_chars=max_chars,
|
|
276
|
+
interval=args.interval)
|
|
111
277
|
out = dumps(r)
|
|
112
278
|
print(out if args.json else out[:2000])
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""crawl_frontier.py — 爬取前沿的质量规则。
|
|
3
|
+
|
|
4
|
+
爬虫的价值不在于抓得多,而在于少抓同一页的不同写法、少抓根本不是页面的东西。
|
|
5
|
+
这里只做三件事,都是抓取前的纯函数判断,不碰网络:
|
|
6
|
+
|
|
7
|
+
1. URL 归一:复用 url_canon 的单一来源(追踪参数、fragment、参数序、尾斜杠),
|
|
8
|
+
另加会话 ID 参数(;jsessionid=、PHPSESSID 等)。
|
|
9
|
+
2. 明显地不该抓的 URL:图片/音视频/压缩包/字体/脚本样式等静态资产,
|
|
10
|
+
以及路径段连续重复三次以上、层级过深、URL 过长的坏链接。
|
|
11
|
+
3. 范围判定:同主机 + 起始路径前缀。auto 模式在起始页是叶子页时上提一层,
|
|
12
|
+
让「从一篇博客进入」也能覆盖同栏目的其他文章。
|
|
13
|
+
|
|
14
|
+
不做模板陷阱学习与 DUST 改写规则(需要跨页统计,属第二阶段);这里保持纯函数,
|
|
15
|
+
调用方自己持有已访问集合与内容哈希。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import html as _html
|
|
21
|
+
import re
|
|
22
|
+
from urllib.parse import urldefrag, urljoin, urlparse
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from url_canon import canonical_url
|
|
26
|
+
except ImportError: # pragma: no cover - 脚本目录不在 sys.path 时退回原样
|
|
27
|
+
def canonical_url(url: str, **_kwargs) -> str: # type: ignore
|
|
28
|
+
return url
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# 静态资产后缀:fetch_v3 的正文提取对这些没有收益,抓了只会浪费一次请求。
|
|
32
|
+
_ASSET_SUFFIXES = frozenset({
|
|
33
|
+
".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".ico", ".bmp", ".avif",
|
|
34
|
+
".tif", ".tiff", ".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac", ".opus",
|
|
35
|
+
".mp4", ".webm", ".mov", ".avi", ".mkv", ".m3u8", ".mpd",
|
|
36
|
+
".zip", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".tar",
|
|
37
|
+
".woff", ".woff2", ".ttf", ".otf", ".eot",
|
|
38
|
+
".exe", ".dmg", ".pkg", ".deb", ".rpm", ".apk", ".ipa",
|
|
39
|
+
".css", ".js", ".mjs", ".cjs", ".map",
|
|
40
|
+
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".epub",
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
# 会话 ID 参数:值通常随机且每次不同,会把同一页拆成无限多个 URL。
|
|
44
|
+
_SESSION_PARAMS = frozenset({
|
|
45
|
+
"jsessionid", "phpsessid", "sessionid", "session_id", "zenid", "oscsid",
|
|
46
|
+
"cfid", "cftoken",
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
_MAX_URL_LEN = 2048
|
|
50
|
+
_MAX_DEPTH = 8
|
|
51
|
+
_MAX_QUERY_LEN = 512
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def canonical(url: str, base: str = "") -> str:
|
|
55
|
+
"""绝对化 + 归一化。解析失败时原样返回(fail-open,不让坏 URL 中断整次爬取)。
|
|
56
|
+
|
|
57
|
+
fold_scheme=False:归一化的结果会被当成实际抓取地址,http 折成 https 会
|
|
58
|
+
悄悄改变请求协议(有些站只有 http)。去重仍能覆盖追踪参数、参数序、
|
|
59
|
+
www/mobile、尾斜杠这些真正的重复写法。
|
|
60
|
+
"""
|
|
61
|
+
if base:
|
|
62
|
+
url = urljoin(base, url)
|
|
63
|
+
url, _fragment = urldefrag(url)
|
|
64
|
+
try:
|
|
65
|
+
return canonical_url(url, fold_scheme=False)
|
|
66
|
+
except Exception:
|
|
67
|
+
return url
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def strip_session_params(url: str) -> str:
|
|
71
|
+
"""删掉路径里的 ;jsessionid=... 与会话类查询参数。"""
|
|
72
|
+
parsed = urlparse(url)
|
|
73
|
+
path = re.sub(r";(?:%s)=[^/]*" % "|".join(_SESSION_PARAMS), "", parsed.path,
|
|
74
|
+
flags=re.IGNORECASE)
|
|
75
|
+
if not parsed.query:
|
|
76
|
+
return parsed._replace(path=path).geturl() if path != parsed.path else url
|
|
77
|
+
kept = []
|
|
78
|
+
for part in parsed.query.split("&"):
|
|
79
|
+
name = part.split("=", 1)[0].lower()
|
|
80
|
+
if name in _SESSION_PARAMS:
|
|
81
|
+
continue
|
|
82
|
+
kept.append(part)
|
|
83
|
+
query = "&".join(kept)
|
|
84
|
+
return parsed._replace(path=path, query=query).geturl()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def is_asset(url: str) -> bool:
|
|
88
|
+
"""路径后缀是静态资产即判定为不该按页面抓取。"""
|
|
89
|
+
path = urlparse(url).path.lower()
|
|
90
|
+
dot = path.rfind(".")
|
|
91
|
+
if dot < 0:
|
|
92
|
+
return False
|
|
93
|
+
suffix = path[dot:]
|
|
94
|
+
return suffix in _ASSET_SUFFIXES
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def is_pathological(url: str) -> bool:
|
|
98
|
+
"""坏链接的确定性判据:重复路径段、层级过深、URL 过长。
|
|
99
|
+
|
|
100
|
+
重复段规则取自 Heritrix 的 PathologicalPath:坏掉的相对链接会把 `more/`
|
|
101
|
+
越叠越长,`/a/more/more/more` 这类 URL 永远抓不完。
|
|
102
|
+
"""
|
|
103
|
+
if len(url) > _MAX_URL_LEN:
|
|
104
|
+
return True
|
|
105
|
+
parsed = urlparse(url)
|
|
106
|
+
if len(parsed.query) > _MAX_QUERY_LEN:
|
|
107
|
+
return True
|
|
108
|
+
path = parsed.path or "/"
|
|
109
|
+
if re.search(r"(/[^/]+)\1{2,}", path):
|
|
110
|
+
return True
|
|
111
|
+
depth = len([seg for seg in path.split("/") if seg])
|
|
112
|
+
return depth > _MAX_DEPTH
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def looks_html(html: str) -> bool:
|
|
116
|
+
"""没有可靠的 Content-Type 时按内容嗅探:只要出现标签就算 HTML。
|
|
117
|
+
|
|
118
|
+
fetch_v3 的批量入口不返回响应头,扩展名过滤之后仍有大量无后缀的
|
|
119
|
+
`/api/...`、`/download/...`;这里只排除明确的非 HTML(XML/JSON/PDF/空响应),
|
|
120
|
+
片段(`<a href=...>`)也当页面——旧版测试与真实站的局部渲染都会给片段。
|
|
121
|
+
"""
|
|
122
|
+
head = (html or "")[:4096].lstrip().lower()
|
|
123
|
+
if not head:
|
|
124
|
+
return False
|
|
125
|
+
if head.startswith(("<?xml", "{", "[", "%pdf")):
|
|
126
|
+
return False
|
|
127
|
+
return "<" in head and ">" in head
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def extract_links(html: str, base: str) -> list[str]:
|
|
131
|
+
"""提取 href,绝对化后按归一化 URL 去重;不做资产/范围判断(调用方分层)。"""
|
|
132
|
+
out: list[str] = []
|
|
133
|
+
seen: set[str] = set()
|
|
134
|
+
for match in re.finditer(r"""href\s*=\s*["']([^"'#]+)""", html or "",
|
|
135
|
+
flags=re.IGNORECASE):
|
|
136
|
+
raw = _html.unescape(match.group(1).strip())
|
|
137
|
+
if not raw or raw.lower().startswith(("javascript:", "mailto:", "tel:",
|
|
138
|
+
"data:", "javascript:")):
|
|
139
|
+
continue
|
|
140
|
+
absolute = urljoin(base, raw)
|
|
141
|
+
scheme = urlparse(absolute).scheme.lower()
|
|
142
|
+
if scheme not in ("http", "https"):
|
|
143
|
+
continue
|
|
144
|
+
key = canonical(strip_session_params(absolute))
|
|
145
|
+
if key in seen:
|
|
146
|
+
continue
|
|
147
|
+
seen.add(key)
|
|
148
|
+
out.append(key)
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def scope_prefix(start_url: str, scope: str = "auto") -> str:
|
|
153
|
+
"""返回路径前缀;`/` 表示整个主机。
|
|
154
|
+
|
|
155
|
+
auto:把末段当作叶子页(有无扩展名都算),上提到所在目录;目录型种子
|
|
156
|
+
(以 / 结尾)保持原样。这样从一篇博客进入能覆盖同栏目,而不是只抓这一篇。
|
|
157
|
+
path:严格按起始路径前缀,末段不带 / 时补上,等于只抓该路径下面的页。
|
|
158
|
+
"""
|
|
159
|
+
path = urlparse(start_url).path or "/"
|
|
160
|
+
if scope == "domain":
|
|
161
|
+
return "/"
|
|
162
|
+
segments = [seg for seg in path.split("/") if seg]
|
|
163
|
+
if scope == "path":
|
|
164
|
+
return path if path.endswith("/") else path + "/"
|
|
165
|
+
# auto
|
|
166
|
+
if path.endswith("/"):
|
|
167
|
+
return path
|
|
168
|
+
if not segments:
|
|
169
|
+
return "/"
|
|
170
|
+
# 叶子页(/blog/post.html 或 /blog/post)上提到它所在的栏目目录,而不是
|
|
171
|
+
# 直接退到根:否则从一篇博客进入会把整站都当成范围。和 PageSift 的
|
|
172
|
+
# --scope auto「叶子种子扩到栏目」同义。
|
|
173
|
+
parent = "/" + "/".join(segments[:-1]) if len(segments) > 1 else ""
|
|
174
|
+
return (parent + "/") if parent else "/"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Frontier:
|
|
178
|
+
"""持有一段爬取的起始主机、路径前缀与子域开关。"""
|
|
179
|
+
|
|
180
|
+
def __init__(self, start_url: str, scope: str = "auto",
|
|
181
|
+
subdomains: bool = False):
|
|
182
|
+
parsed = urlparse(start_url)
|
|
183
|
+
self.start_url = start_url
|
|
184
|
+
self.host = parsed.netloc.lower()
|
|
185
|
+
self.root_host = parsed.hostname.lower() if parsed.hostname else ""
|
|
186
|
+
self.prefix = scope_prefix(start_url, scope)
|
|
187
|
+
self.scope = scope
|
|
188
|
+
self.subdomains = subdomains
|
|
189
|
+
|
|
190
|
+
def _host_ok(self, url: str) -> bool:
|
|
191
|
+
parsed = urlparse(url)
|
|
192
|
+
host = parsed.netloc.lower()
|
|
193
|
+
if host == self.host:
|
|
194
|
+
return True
|
|
195
|
+
if not self.subdomains:
|
|
196
|
+
return False
|
|
197
|
+
name = parsed.hostname or ""
|
|
198
|
+
return bool(self.root_host) and (name == self.root_host
|
|
199
|
+
or name.endswith("." + self.root_host))
|
|
200
|
+
|
|
201
|
+
def _path_ok(self, url: str) -> bool:
|
|
202
|
+
if self.prefix == "/":
|
|
203
|
+
return True
|
|
204
|
+
path = urlparse(url).path or "/"
|
|
205
|
+
return path == self.prefix.rstrip("/") or path.startswith(self.prefix)
|
|
206
|
+
|
|
207
|
+
def accept(self, url: str) -> tuple[bool, str]:
|
|
208
|
+
"""返回 (是否接受, 拒绝原因)。原因用于汇总统计,不进上下文。"""
|
|
209
|
+
if not self._host_ok(url):
|
|
210
|
+
return False, "offsite"
|
|
211
|
+
if is_asset(url):
|
|
212
|
+
return False, "asset"
|
|
213
|
+
if is_pathological(url):
|
|
214
|
+
return False, "pathological"
|
|
215
|
+
if not self._path_ok(url):
|
|
216
|
+
return False, "out_of_scope"
|
|
217
|
+
return True, ""
|