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.
Files changed (90) hide show
  1. package/README.en.md +24 -21
  2. package/README.es.md +24 -21
  3. package/README.ja.md +23 -20
  4. package/README.ko.md +23 -20
  5. package/README.md +26 -21
  6. package/SKILL.md +5 -5
  7. package/backends/domain_profiles.json +76 -0
  8. package/backends/engine_registry.yaml +161 -5
  9. package/backends/quota_profiles.json +122 -2
  10. package/bin/argo +22 -1
  11. package/bin/argo.js +3 -3
  12. package/config.yaml +128 -21
  13. package/docs/ARGO_INTRO.md +4 -4
  14. package/docs/ENGINE_CATALOG.md +64 -44
  15. package/docs/MCP_SETUP.md +1 -1
  16. package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
  17. package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
  18. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
  19. package/engines/specs/clawhub.yaml +16 -15
  20. package/engines/specs/deepseek1024.yaml +46 -0
  21. package/engines/specs/dsh_hub.yaml +44 -0
  22. package/engines/specs/dshopen.yaml +32 -0
  23. package/engines/specs/explainx.yaml +32 -0
  24. package/engines/specs/gbfs_nyc.yaml +6 -1
  25. package/engines/specs/metaso_doc.yaml +49 -0
  26. package/engines/specs/metaso_image.yaml +65 -0
  27. package/engines/specs/metaso_podcast.yaml +60 -0
  28. package/engines/specs/metaso_scholar.yaml +57 -0
  29. package/engines/specs/metaso_video.yaml +62 -0
  30. package/engines/specs/ncpssd.yaml +41 -0
  31. package/engines/specs/sciverse.yaml +72 -0
  32. package/engines/specs/skills_sh.yaml +32 -0
  33. package/engines/specs/skillsmp.yaml +18 -16
  34. package/package.json +3 -2
  35. package/packages/dsh-plugin/README.md +3 -2
  36. package/packages/dsh-plugin/package.json +1 -1
  37. package/packages/dsh-plugin/test/size-gate.test.js +113 -0
  38. package/scripts/adaptive.py +41 -14
  39. package/scripts/article.py +6 -1
  40. package/scripts/article_meta.py +151 -2
  41. package/scripts/bench_general_pool.py +145 -0
  42. package/scripts/candidate_envelope.py +45 -4
  43. package/scripts/charset_decode.py +127 -0
  44. package/scripts/crawl.py +240 -74
  45. package/scripts/crawl_frontier.py +217 -0
  46. package/scripts/crawl_policy.py +174 -0
  47. package/scripts/engine_dispatch.py +22 -15
  48. package/scripts/engine_failure.py +15 -0
  49. package/scripts/engine_validate.py +8 -0
  50. package/scripts/engines.py +10 -0
  51. package/scripts/engines_base.py +12 -0
  52. package/scripts/engines_builders.py +14 -0
  53. package/scripts/engines_builders_dsh.py +330 -0
  54. package/scripts/engines_builders_skill.py +314 -0
  55. package/scripts/fetch_v3.py +37 -5
  56. package/scripts/gen_engine_catalog.py +218 -2
  57. package/scripts/general_pool.py +162 -0
  58. package/scripts/http_client.py +38 -42
  59. package/scripts/image_ops.py +4 -0
  60. package/scripts/install.ps1 +47 -19
  61. package/scripts/install.sh +45 -20
  62. package/scripts/matrix_search_eval.py +17 -1
  63. package/scripts/mcp_transport.py +1 -1
  64. package/scripts/ncpssd_bridge.py +123 -0
  65. package/scripts/paid_policy.py +109 -13
  66. package/scripts/pre-commit +19 -4
  67. package/scripts/query_signals.py +156 -3
  68. package/scripts/redskill/redskill_engine.py +29 -2
  69. package/scripts/release_check.py +209 -0
  70. package/scripts/retry_policy.py +22 -1
  71. package/scripts/robots_guard.py +26 -0
  72. package/scripts/route.py +11 -8
  73. package/scripts/route_cache.py +6 -0
  74. package/scripts/route_combo.py +37 -59
  75. package/scripts/route_domains.py +4 -1
  76. package/scripts/route_policy.py +6 -0
  77. package/scripts/search.py +9 -1
  78. package/scripts/search_cli.py +27 -0
  79. package/scripts/search_entry.py +9 -0
  80. package/scripts/search_output.py +29 -0
  81. package/scripts/search_pipeline.py +39 -1
  82. package/scripts/search_rank.py +1 -0
  83. package/scripts/social_engines/bilibili_engine.py +163 -26
  84. package/scripts/social_engines/reddit_engine.py +52 -51
  85. package/scripts/source_selection.py +302 -0
  86. package/scripts/video_fetch.py +303 -0
  87. package/scripts/video_meta.py +225 -0
  88. package/scripts/video_route.py +65 -0
  89. package/scripts/watch.py +123 -0
  90. 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
- import re, time
4
- from urllib.parse import urljoin, urlparse
5
- from bounded_run import run_bounded, TaskError
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
- # fetch_v3 而非裸 urllib fetch:UA 轮换 + Cookie 积累 + curl_cffi 指纹伪造,
8
- # 反爬站(CF 保护等)从必然失败到大概率成功。批量场景禁浏览器降级
9
- # (BFS 可能爬几十页,每页启动 Chrome CDP 会拖慢整体)。
10
- from fetch_v3 import fetch_page_v3 as _fetch_page_v3
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
- return fetch_page(url, max_chars=max_chars, timeout=timeout, raw=raw)
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
- fetch_page = _fetch_page_v3
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
- def crawl_sitemap(url, max_pages=20, timeout=10):
27
- """从 sitemap.xml 爬取"""
28
- t0 = time.monotonic()
29
- sitemap_url = urljoin(url, '/sitemap.xml')
30
- result = _crawl_fetch(sitemap_url, 50000, timeout)
31
- if not result['success']:
32
- # 尝试 robots.txt 指定的 sitemap
33
- robots_url = urljoin(url, '/robots.txt')
34
- robots_result = _crawl_fetch(robots_url, 10000, timeout)
35
- if robots_result['success'] and 'Sitemap:' in robots_result.get('html', ''):
36
- import re as _re
37
- sitemap_urls = _re.findall(r'Sitemap:\s*(.+)', robots_result['html'])
38
- if sitemap_urls:
39
- sitemap_url = sitemap_urls[0].strip()
40
- result = _crawl_fetch(sitemap_url, 50000, timeout)
41
- if not result.get('success') or not result.get('html'):
42
- return {'url': url, 'pages': [], 'total': 0, 'error': 'sitemap not found or empty'}
43
- html = result.get('html') or result.get('content') or ''
44
- urls = re.findall(r'<loc>\s*(.*?)\s*</loc>', html)
45
- urls = urls[:max_pages]
46
- pages = []
47
- # 总时限 timeout*2:到点未抓到的站点跳过,不再被卡住的单个 URL 拖住,也不会
48
- # 因超时异常中断整次 sitemap 爬取。
49
- finished, _unfinished = run_bounded(
50
- urls, lambda u: _crawl_fetch(u, 2000, timeout), timeout * 2, max_workers=5)
51
- for _u, r in finished:
52
- if isinstance(r, TaskError) or not r.get('success'):
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
- pages.append({'url': r['url'], 'content': r['content'][:500], 'depth': 0})
55
- return {'url': url, 'pages': pages, 'total': len(pages), 'elapsed_ms': int((time.monotonic() - t0) * 1000)}
56
-
57
- def crawl_bfs(url, max_pages=10, max_depth=2, timeout=8):
58
- """BFS 爬取(按层并行 frontier,去重后入队)"""
59
- from collections import deque
60
- visited = set()
61
- pages = []
62
- queue = deque([(url, 0)])
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
- # 取一层(最多 5 个)并行抓取
65
- frontier = []
66
- while queue and len(frontier) < 5:
67
- u, d = queue.popleft()
68
- if u in visited or d > max_depth:
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.add(u)
71
- frontier.append((u, d))
72
- if not frontier:
158
+ if candidate in visited:
159
+ continue
160
+ visited.add(candidate)
161
+ batch.append((candidate, depth))
162
+ if not batch:
73
163
  break
74
- # 一层最多 5 个,总时限 timeout*2;到点未完成的 URL 跳过,不被单个慢站拖住。
75
- finished, _unfinished = run_bounded(
76
- frontier, lambda ud: _crawl_fetch(ud[0], 2000, timeout),
77
- timeout * 2, max_workers=min(len(frontier), 5))
78
- for (u, d), result in finished:
79
- if isinstance(result, TaskError) or not result.get('success'):
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
- pages.append({'url': u, 'content': result['content'][:500], 'depth': d})
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
- html = result.get('html') or result.get('content') or ''
85
- links = re.findall(r'href=["\']([^"\'#]+)', html)
86
- for link in links[:5]:
87
- full = urljoin(u, link)
88
- if (urlparse(full).netloc == urlparse(url).netloc
89
- and full not in visited):
90
- queue.append((full, d + 1))
91
- return {'url': url, 'pages': pages, 'total': len(pages)}
92
- if __name__ == '__main__':
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, ""