@jayyuen66/dsh-scrapling 0.0.3 → 0.1.1
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.md +137 -57
- package/README.zh-CN.md +111 -47
- package/THIRD_PARTY_NOTICES.md +7 -7
- package/client.js +85 -36
- package/cordis.patch.yml +3 -3
- package/host.js +25 -18
- package/package.json +57 -48
- package/py/adapters.py +466 -166
- package/py/bridge.py +36 -2
- package/py/crawl.py +99 -6
- package/py/guard.py +5 -25
package/py/bridge.py
CHANGED
|
@@ -41,6 +41,30 @@ import time
|
|
|
41
41
|
import traceback
|
|
42
42
|
from typing import Any, Callable
|
|
43
43
|
|
|
44
|
+
MIN_PYTHON = (3, 14)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_python(version_info: tuple[int, ...] = tuple(sys.version_info[:3])) -> str | None:
|
|
48
|
+
"""低于 3.14 地板时返回给用户的消息,达标返回 None。
|
|
49
|
+
|
|
50
|
+
:param version_info: 要判定的版本;默认当前解释器的前三段,调用方可注入。
|
|
51
|
+
"""
|
|
52
|
+
if (version_info[0], version_info[1]) >= MIN_PYTHON:
|
|
53
|
+
return None
|
|
54
|
+
current = ".".join(str(part) for part in version_info[:3])
|
|
55
|
+
return (
|
|
56
|
+
f"dsh-scrapling 需要 Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+,当前 {current}。"
|
|
57
|
+
"插件用的是 PATH 上的 python3(设置页留空即该解释器),请升级它,或在设置里填 3.14+ 的绝对路径。"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_gate_message = check_python()
|
|
62
|
+
if _gate_message is not None:
|
|
63
|
+
# 走 stderr:stdout 是协议帧通道,往它写一行散文会把整条 JSON-lines 流打坏。
|
|
64
|
+
print(_gate_message, file=sys.stderr)
|
|
65
|
+
raise SystemExit(78)
|
|
66
|
+
|
|
67
|
+
|
|
44
68
|
# 让 py/ 目录里的 guard 能被 adapters 用 `from guard import install` 找到。
|
|
45
69
|
_HERE = __file__.rsplit("/", 1)[0] or "."
|
|
46
70
|
if _HERE not in sys.path:
|
|
@@ -143,7 +167,7 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
|
143
167
|
request_id,
|
|
144
168
|
"DEPENDENCY_MISSING",
|
|
145
169
|
f"缺少可选依赖 {missing},这次调用无法执行。本插件的默认 extractionType 是 "
|
|
146
|
-
f'markdown,需要 scrapling 的 rag extra:pip install "scrapling[rag]>=0.
|
|
170
|
+
f'markdown,需要 scrapling 的 rag extra:pip install "scrapling[rag]>=0.5,<0.6"',
|
|
147
171
|
)
|
|
148
172
|
except Exception as error: # noqa: BLE001 —— 任何异常都要变成一帧错误,不能让线程死掉
|
|
149
173
|
log(f"{method} failed: {type(error).__name__}: {error}")
|
|
@@ -172,7 +196,17 @@ def _worker() -> None:
|
|
|
172
196
|
time.sleep(0.05)
|
|
173
197
|
frame = _drain()
|
|
174
198
|
if frame is None:
|
|
175
|
-
|
|
199
|
+
# 「判定该退出」必须与入队互斥:读者是在 _QUEUE_LOCK 里 append 之后才去数
|
|
200
|
+
# worker 的,而这里在同一个锁里复查队列 —— 否则会出现「_ensure_worker 看到
|
|
201
|
+
# 我还活着所以不补人,我随后就退了」,那一帧被永久搁置在队列里。
|
|
202
|
+
with _QUEUE_LOCK:
|
|
203
|
+
if _QUEUE:
|
|
204
|
+
continue
|
|
205
|
+
with _WORKERS_LOCK:
|
|
206
|
+
current = threading.current_thread()
|
|
207
|
+
if current in _WORKERS:
|
|
208
|
+
_WORKERS.remove(current)
|
|
209
|
+
return
|
|
176
210
|
try:
|
|
177
211
|
emit(handle(frame))
|
|
178
212
|
except Exception as error: # noqa: BLE001 —— 连序列化失败都不能让线程死掉
|
package/py/crawl.py
CHANGED
|
@@ -10,6 +10,7 @@ daemon 线程**跑 spider,主线程立刻返回 crawl id;进度通过「没
|
|
|
10
10
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
|
+
import json
|
|
13
14
|
import threading
|
|
14
15
|
import time
|
|
15
16
|
import uuid
|
|
@@ -35,10 +36,54 @@ MAX_CONCURRENT_CRAWLS = 2
|
|
|
35
36
|
# 结束就删;但全留着就是内存泄漏,所以留一个上限,按最旧的淘汰。
|
|
36
37
|
MAX_REMEMBERED_CRAWLS = 16
|
|
37
38
|
|
|
39
|
+
# 一次 crawl.status 回包的字节上界。Host 侧按 8 MiB 切帧,而一个快站点能在一个轮询间隔里
|
|
40
|
+
# 落下几十页;留一半余量,越过切帧线的那一帧会把整个 sidecar 拆掉。回不完的由 `more` 交接。
|
|
41
|
+
MAX_STATUS_BYTES = 4 * 1024 * 1024
|
|
42
|
+
|
|
38
43
|
# 一次爬虫的整体截止(毫秒)。页数上限管不了「一页等一分钟」:1000 页的慢站点能跑几个
|
|
39
44
|
# 小时,而爬虫跑在没人看的后台线程里,没有任何外部计时器会来叫停它。部署侧可按次调小。
|
|
40
45
|
DEFAULT_MAX_RUNTIME_MS = 1_800_000
|
|
41
46
|
|
|
47
|
+
# 爬虫的默认并发。与 Scrapling 的 Spider 默认值一致(spiders/spider.py 的
|
|
48
|
+
# ``concurrent_requests = 4``),写在这里是为了让「部署没表态」与「部署表态成 4」在
|
|
49
|
+
# 日志里不是同一件事。
|
|
50
|
+
DEFAULT_CONCURRENT_REQUESTS = 4
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _crawl_policy(args: dict[str, Any]) -> dict[str, Any]:
|
|
54
|
+
"""读部署命名空间里的爬虫策略旋钮。
|
|
55
|
+
|
|
56
|
+
全是部署级(不进设置卡、模型入参到不了这里):它们决定的是「这台机器怎么对待别人的
|
|
57
|
+
站点」—— 遵不遵守 robots.txt、隔多久发一个请求、同时开几条连接 —— 那是部署方的表态,
|
|
58
|
+
不是某次会话的偏好。取值一律**报错而不夹**:一个写错的 0 被悄悄抬成 1,读日志的人
|
|
59
|
+
只会以为「配的就是这样」。
|
|
60
|
+
|
|
61
|
+
:param args: 协议参数
|
|
62
|
+
:returns: 交给 Spider 类属性与构造器的那一份
|
|
63
|
+
:raises adapters.AdapterError: 取值非法
|
|
64
|
+
"""
|
|
65
|
+
from adapters import AdapterError, _positive_int
|
|
66
|
+
|
|
67
|
+
deployment = args.get("deployment")
|
|
68
|
+
knobs: dict[str, Any] = deployment if isinstance(deployment, dict) else {}
|
|
69
|
+
strategy = knobs.get("crawlStrategy", "bfs")
|
|
70
|
+
if strategy not in ("bfs", "dfs"):
|
|
71
|
+
raise AdapterError("BAD_ARGS", f"crawlStrategy must be 'bfs' or 'dfs', got {strategy!r}")
|
|
72
|
+
delay_ms = knobs.get("crawlDownloadDelayMs", 0)
|
|
73
|
+
if not isinstance(delay_ms, (int, float)) or isinstance(delay_ms, bool) or delay_ms < 0:
|
|
74
|
+
raise AdapterError("BAD_ARGS", "crawlDownloadDelayMs must be a non-negative number")
|
|
75
|
+
checkpoint_dir = knobs.get("crawlCheckpointDir")
|
|
76
|
+
return {
|
|
77
|
+
"strategy": strategy,
|
|
78
|
+
"delay_seconds": float(delay_ms) / 1000.0,
|
|
79
|
+
"concurrency": _positive_int(
|
|
80
|
+
knobs.get("crawlConcurrentRequests"), "crawlConcurrentRequests", DEFAULT_CONCURRENT_REQUESTS
|
|
81
|
+
),
|
|
82
|
+
"obey_robots": knobs.get("crawlRespectRobots") is True,
|
|
83
|
+
"autothrottle": knobs.get("crawlAutothrottle") is True,
|
|
84
|
+
"checkpoint_dir": checkpoint_dir if isinstance(checkpoint_dir, str) else "",
|
|
85
|
+
}
|
|
86
|
+
|
|
42
87
|
|
|
43
88
|
def _clip_markdown(text: str, budget: int) -> str:
|
|
44
89
|
"""把单页正文封顶到 budget 字符。
|
|
@@ -107,18 +152,21 @@ def _make_spider(
|
|
|
107
152
|
crawl_id: str,
|
|
108
153
|
state: dict[str, Any],
|
|
109
154
|
domains: set[str],
|
|
155
|
+
policy: dict[str, Any],
|
|
110
156
|
) -> Any:
|
|
111
157
|
"""动态造一个 spider 类。
|
|
112
158
|
|
|
113
159
|
Spider 的 ``start_urls`` / ``allowed_domains`` / ``max_pages`` / ``output_dir``
|
|
114
160
|
都是**类属性**而不是 ``__init__`` 参数 —— ``Spider.__init__`` 只收 crawldir 与
|
|
115
|
-
interval,当构造参数传会直接 TypeError
|
|
161
|
+
interval,当构造参数传会直接 TypeError。所以只能在类体上写。待站策略(robots.txt、
|
|
162
|
+
限速、并发、抓取顺序)同理,它们也是 Spider 的类属性。
|
|
116
163
|
|
|
117
164
|
:param url: 起始 URL
|
|
118
165
|
:param limit: 最多爬多少页
|
|
119
166
|
:param crawl_id: 爬虫 id,用于日志
|
|
120
167
|
:param state: 结果槽;爬完写进它
|
|
121
168
|
:param domains: 起始域集合,链接发现与收页复核共用同一份
|
|
169
|
+
:param policy: ``_crawl_policy`` 读出的待站策略
|
|
122
170
|
:returns: spider 实例
|
|
123
171
|
"""
|
|
124
172
|
from scrapling.spiders import SiteToMarkdownSpider
|
|
@@ -131,6 +179,13 @@ def _make_spider(
|
|
|
131
179
|
allowed_domains = domains
|
|
132
180
|
max_pages = limit
|
|
133
181
|
output_dir = None
|
|
182
|
+
# 待站策略。robots_txt_obey 打开后 0.5 会把「取不到 robots.txt」当成禁止爬该域
|
|
183
|
+
# (0.4.15 是放行),所以这一档要么别开,要么确保那台站点的 robots.txt 取得回来。
|
|
184
|
+
robots_txt_obey = policy["obey_robots"]
|
|
185
|
+
download_delay = policy["delay_seconds"]
|
|
186
|
+
concurrent_requests = policy["concurrency"]
|
|
187
|
+
crawl_strategy = policy["strategy"]
|
|
188
|
+
autothrottle_enabled = policy["autothrottle"]
|
|
134
189
|
|
|
135
190
|
def configure_sessions(self, manager: Any) -> None:
|
|
136
191
|
"""把爬虫的会话换成「只跟安全重定向、走配置里那份代理」的那一份。
|
|
@@ -225,7 +280,7 @@ def _make_spider(
|
|
|
225
280
|
)
|
|
226
281
|
return None
|
|
227
282
|
|
|
228
|
-
return Collector()
|
|
283
|
+
return Collector(crawldir=policy["checkpoint_dir"] or None)
|
|
229
284
|
|
|
230
285
|
|
|
231
286
|
def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
@@ -248,6 +303,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
248
303
|
max_content_chars = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
249
304
|
budget_ms = _positive_int(args.get("maxDurationMs"), "maxDurationMs", DEFAULT_MAX_RUNTIME_MS)
|
|
250
305
|
strip_inline_images = _strip_inline_images(args)
|
|
306
|
+
policy = _crawl_policy(args)
|
|
251
307
|
crawl_id = uuid.uuid4().hex[:12]
|
|
252
308
|
state: dict[str, Any] = {
|
|
253
309
|
"error": None,
|
|
@@ -284,7 +340,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
284
340
|
}
|
|
285
341
|
|
|
286
342
|
try:
|
|
287
|
-
spider = _make_spider(url, max_pages, crawl_id, state, domains)
|
|
343
|
+
spider = _make_spider(url, max_pages, crawl_id, state, domains, policy)
|
|
288
344
|
except BaseException as error:
|
|
289
345
|
with _CRAWL_LOCK:
|
|
290
346
|
_CRAWLS.pop(crawl_id, None)
|
|
@@ -370,27 +426,64 @@ def _get_crawl(crawl_id: Any) -> dict[str, Any]:
|
|
|
370
426
|
def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
371
427
|
"""查一个爬虫的状态与已收结果。
|
|
372
428
|
|
|
429
|
+
``since`` 是本轮之前已经读走多少页(按下标,不是 URL)。带上它只回新增的那一段:
|
|
430
|
+
整份 pages 每轮重发,流量是 O(n²)。但增量本身也可能很大 —— 一个快站点能在一个轮询
|
|
431
|
+
间隔里落下几十页,每页又按 ``max_content_chars`` 封顶 —— 而 Host 侧是按 8 MiB 切帧的:
|
|
432
|
+
超了就是一帧坏帧,整个 sidecar 连同正在跑的会话一起被拆掉。所以回包再按**字节**分片:
|
|
433
|
+
回不完就置 ``more``,调用方拿新的 ``since`` 立刻接着取,一页都不丢。
|
|
434
|
+
|
|
373
435
|
:param args: 协议参数
|
|
374
|
-
:returns: {crawlId, running, pages, error, expired}
|
|
436
|
+
:returns: {crawlId, running, pages, total, error, expired, more}
|
|
375
437
|
"""
|
|
438
|
+
from adapters import AdapterError
|
|
439
|
+
|
|
440
|
+
since = args.get("since", 0)
|
|
441
|
+
if not isinstance(since, int) or isinstance(since, bool) or since < 0:
|
|
442
|
+
raise AdapterError("BAD_ARGS", "since must be a non-negative integer")
|
|
376
443
|
entry = _get_crawl(args.get("crawlId"))
|
|
377
444
|
state: dict[str, Any] = entry["state"]
|
|
378
445
|
# pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
|
|
379
|
-
#
|
|
446
|
+
# 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
380
447
|
with _CRAWL_LOCK:
|
|
381
|
-
|
|
448
|
+
total = len(state["pages"])
|
|
449
|
+
pages, more = _take_pages(state["pages"], since)
|
|
382
450
|
running = _is_running(entry)
|
|
383
451
|
return {
|
|
384
452
|
"crawlId": entry["crawl_id"],
|
|
385
453
|
# thread 为 None 表示 spider 还在构造中:没跑起来,但也没结束。
|
|
386
454
|
"running": running,
|
|
387
455
|
"pages": pages,
|
|
456
|
+
"total": total,
|
|
457
|
+
"more": more,
|
|
388
458
|
"error": state["error"],
|
|
389
459
|
# 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
|
|
390
460
|
"expired": state.get("expired") is True,
|
|
391
461
|
}
|
|
392
462
|
|
|
393
463
|
|
|
464
|
+
def _take_pages(all_pages: list[dict[str, Any]], since: int) -> tuple[list[dict[str, Any]], bool]:
|
|
465
|
+
"""从 ``since`` 起取一段页,按 :data:`MAX_STATUS_BYTES` 封顶。
|
|
466
|
+
|
|
467
|
+
至少回一页:单页就超预算时也回它,否则调用方永远取不到下一页,轮询变成死循环。
|
|
468
|
+
单页体量由 ``max_content_chars`` 兜着,一页远小于 Host 那份 8 MiB 切帧上限。
|
|
469
|
+
|
|
470
|
+
:param all_pages - 活页表
|
|
471
|
+
:param since - 已经读走多少页
|
|
472
|
+
:returns: (这一段的页, 后面还有没有)
|
|
473
|
+
"""
|
|
474
|
+
if since >= len(all_pages):
|
|
475
|
+
return [], False
|
|
476
|
+
taken: list[dict[str, Any]] = []
|
|
477
|
+
spent = 0
|
|
478
|
+
for index in range(since, len(all_pages)):
|
|
479
|
+
size = len(json.dumps(all_pages[index], ensure_ascii=False).encode("utf-8"))
|
|
480
|
+
if taken and spent + size > MAX_STATUS_BYTES:
|
|
481
|
+
return taken, True
|
|
482
|
+
taken.append(all_pages[index])
|
|
483
|
+
spent += size
|
|
484
|
+
return taken, False
|
|
485
|
+
|
|
486
|
+
|
|
394
487
|
def crawl_stop(args: dict[str, Any]) -> dict[str, Any]:
|
|
395
488
|
"""叫停一个爬虫。
|
|
396
489
|
|
package/py/guard.py
CHANGED
|
@@ -27,9 +27,6 @@ from urllib.parse import unquote, urlparse
|
|
|
27
27
|
# 放行的额外主机名。默认空 —— 只有字面量公网 IP 与解析到公网的域名能过。
|
|
28
28
|
ALLOWED_HOSTS: frozenset[str] = frozenset()
|
|
29
29
|
|
|
30
|
-
# 额外放行的端口;空表示不限端口(与 dsh 内置 fetch provider 同取舍)。
|
|
31
|
-
ALLOWED_PORTS: frozenset[int] = frozenset()
|
|
32
|
-
|
|
33
30
|
# 允许额外放行主机名的环境变量。默认不设 ⇒ 放行集合为空 ⇒ 守卫最严。
|
|
34
31
|
#
|
|
35
32
|
# 这是一个**安全相关**开关:把它指到内网地址等于主动放弃对那些目标的 SSRF 防护。
|
|
@@ -113,19 +110,6 @@ _BYPASS_ENTRIES: tuple[str, ...] = ()
|
|
|
113
110
|
_PROXY_SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
|
114
111
|
_BROWSER_PROXY_SCHEMES = ("http", "https", "socks4", "socks5")
|
|
115
112
|
|
|
116
|
-
# Chromium 的 WebRTC 会绕过 HTTP/SOCKS 代理直接发 UDP,于是页面里一句 STUN 就能问出
|
|
117
|
-
# 访客的真实出口 IP —— 对「我要走代理」的部署方来说,那等于代理白配。这对 flag 让非代理
|
|
118
|
-
# UDP 一律不走;Playwright 不暴露对应开关(patchright 那边有 block_webrtc),只能从启动
|
|
119
|
-
# 参数进去。
|
|
120
|
-
#
|
|
121
|
-
# **两条一起**才是等价物:上游 `block_webrtc=True` 下的就是这两条(_base.py
|
|
122
|
-
# `__generate_stealth_options`)—— 只带 `--force-...=disable_non_proxied_udp` 那一条时
|
|
123
|
-
# 策略并未强制生效。之前这里只有一条,与它想替代的开关并不等价。
|
|
124
|
-
WEBRTC_NO_LEAK_FLAGS = (
|
|
125
|
-
"--webrtc-ip-handling-policy=disable_non_proxied_udp",
|
|
126
|
-
"--force-webrtc-ip-handling-policy",
|
|
127
|
-
)
|
|
128
|
-
|
|
129
113
|
# 额外的 NAT64 前缀(CIDR 字符串)。IPv6 地址命中其中之一时,会抽出内嵌 IPv4 复判;
|
|
130
114
|
# 运营商自建前缀必须在这里声明,否则藏在 IPv6 里的私网 IPv4 会被当成公网放行。
|
|
131
115
|
EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
|
|
@@ -134,21 +118,18 @@ EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
|
|
|
134
118
|
_NAT64_EMBEDDED_OFFSET: dict[int, int] = {96: 12, 64: 9, 56: 7, 48: 6, 40: 5, 32: 4}
|
|
135
119
|
|
|
136
120
|
|
|
137
|
-
def configure(allowed_hosts=None,
|
|
121
|
+
def configure(allowed_hosts=None, nat64_prefixes=None, allow_write_methods=None) -> None:
|
|
138
122
|
"""按部署配置收紧或放宽放行集合。
|
|
139
123
|
|
|
140
124
|
只应由宿主侧在启动时调用一次,参数来自用户显式设置,而不是模型入参。
|
|
141
125
|
|
|
142
126
|
:param allowed_hosts: 额外放行的主机名;None 表示沿用当前值
|
|
143
|
-
:param allowed_ports: 额外放行的端口;None 表示沿用当前值
|
|
144
127
|
:param nat64_prefixes: 额外的 NAT64 前缀(CIDR);None 表示沿用当前值
|
|
145
128
|
:param allow_write_methods: 是否开放写方法;None 表示沿用当前值
|
|
146
129
|
"""
|
|
147
|
-
global ALLOWED_HOSTS,
|
|
130
|
+
global ALLOWED_HOSTS, EXTRA_NAT64_PREFIXES, ALLOW_WRITE_METHODS # noqa: PLW0603 —— 模块级策略常量,需整体替换
|
|
148
131
|
if allowed_hosts is not None:
|
|
149
132
|
ALLOWED_HOSTS = allowed_hosts
|
|
150
|
-
if allowed_ports is not None:
|
|
151
|
-
ALLOWED_PORTS = allowed_ports
|
|
152
133
|
if nat64_prefixes is not None:
|
|
153
134
|
EXTRA_NAT64_PREFIXES = nat64_prefixes
|
|
154
135
|
if allow_write_methods is not None:
|
|
@@ -338,7 +319,7 @@ def _run_readonly(argv: list[str]) -> str:
|
|
|
338
319
|
timeout=3,
|
|
339
320
|
check=False,
|
|
340
321
|
)
|
|
341
|
-
except
|
|
322
|
+
except OSError, ValueError, subprocess.SubprocessError:
|
|
342
323
|
return ""
|
|
343
324
|
return done.stdout
|
|
344
325
|
|
|
@@ -812,11 +793,10 @@ def url_allowed(url: str) -> tuple[bool, str]:
|
|
|
812
793
|
if not host:
|
|
813
794
|
return False, "URL has no host"
|
|
814
795
|
try:
|
|
815
|
-
|
|
796
|
+
_ = parsed.port
|
|
816
797
|
except ValueError:
|
|
798
|
+
# 端口超界(如 :99999)时 urlparse 只在取 .port 那一刻才抛,hostname 本身是好的。
|
|
817
799
|
return False, "URL has an invalid port"
|
|
818
|
-
if ALLOWED_PORTS and port is not None and port not in ALLOWED_PORTS:
|
|
819
|
-
return False, f"port {port} is not in the allow list"
|
|
820
800
|
if not is_public_address(host, proxied=bool(proxy_for(url))):
|
|
821
801
|
return False, f"host does not resolve to a public address: {host}"
|
|
822
802
|
return True, ""
|