@jayyuen66/dsh-scrapling 0.0.3 → 0.1.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.md +129 -56
- package/README.zh-CN.md +103 -46
- package/THIRD_PARTY_NOTICES.md +7 -7
- package/client.js +54 -30
- package/cordis.patch.yml +3 -3
- package/host.js +25 -18
- package/package.json +57 -48
- package/py/adapters.py +440 -153
- package/py/bridge.py +25 -1
- package/py/crawl.py +68 -5
- package/py/guard.py +1 -14
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}")
|
package/py/crawl.py
CHANGED
|
@@ -39,6 +39,46 @@ MAX_REMEMBERED_CRAWLS = 16
|
|
|
39
39
|
# 小时,而爬虫跑在没人看的后台线程里,没有任何外部计时器会来叫停它。部署侧可按次调小。
|
|
40
40
|
DEFAULT_MAX_RUNTIME_MS = 1_800_000
|
|
41
41
|
|
|
42
|
+
# 爬虫的默认并发。与 Scrapling 的 Spider 默认值一致(spiders/spider.py 的
|
|
43
|
+
# ``concurrent_requests = 4``),写在这里是为了让「部署没表态」与「部署表态成 4」在
|
|
44
|
+
# 日志里不是同一件事。
|
|
45
|
+
DEFAULT_CONCURRENT_REQUESTS = 4
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _crawl_policy(args: dict[str, Any]) -> dict[str, Any]:
|
|
49
|
+
"""读部署命名空间里的爬虫策略旋钮。
|
|
50
|
+
|
|
51
|
+
全是部署级(不进设置卡、模型入参到不了这里):它们决定的是「这台机器怎么对待别人的
|
|
52
|
+
站点」—— 遵不遵守 robots.txt、隔多久发一个请求、同时开几条连接 —— 那是部署方的表态,
|
|
53
|
+
不是某次会话的偏好。取值一律**报错而不夹**:一个写错的 0 被悄悄抬成 1,读日志的人
|
|
54
|
+
只会以为「配的就是这样」。
|
|
55
|
+
|
|
56
|
+
:param args: 协议参数
|
|
57
|
+
:returns: 交给 Spider 类属性与构造器的那一份
|
|
58
|
+
:raises adapters.AdapterError: 取值非法
|
|
59
|
+
"""
|
|
60
|
+
from adapters import AdapterError, _positive_int
|
|
61
|
+
|
|
62
|
+
deployment = args.get("deployment")
|
|
63
|
+
knobs: dict[str, Any] = deployment if isinstance(deployment, dict) else {}
|
|
64
|
+
strategy = knobs.get("crawlStrategy", "bfs")
|
|
65
|
+
if strategy not in ("bfs", "dfs"):
|
|
66
|
+
raise AdapterError("BAD_ARGS", f"crawlStrategy must be 'bfs' or 'dfs', got {strategy!r}")
|
|
67
|
+
delay_ms = knobs.get("crawlDownloadDelayMs", 0)
|
|
68
|
+
if not isinstance(delay_ms, (int, float)) or isinstance(delay_ms, bool) or delay_ms < 0:
|
|
69
|
+
raise AdapterError("BAD_ARGS", "crawlDownloadDelayMs must be a non-negative number")
|
|
70
|
+
checkpoint_dir = knobs.get("crawlCheckpointDir")
|
|
71
|
+
return {
|
|
72
|
+
"strategy": strategy,
|
|
73
|
+
"delay_seconds": float(delay_ms) / 1000.0,
|
|
74
|
+
"concurrency": _positive_int(
|
|
75
|
+
knobs.get("crawlConcurrentRequests"), "crawlConcurrentRequests", DEFAULT_CONCURRENT_REQUESTS
|
|
76
|
+
),
|
|
77
|
+
"obey_robots": knobs.get("crawlRespectRobots") is True,
|
|
78
|
+
"autothrottle": knobs.get("crawlAutothrottle") is True,
|
|
79
|
+
"checkpoint_dir": checkpoint_dir if isinstance(checkpoint_dir, str) else "",
|
|
80
|
+
}
|
|
81
|
+
|
|
42
82
|
|
|
43
83
|
def _clip_markdown(text: str, budget: int) -> str:
|
|
44
84
|
"""把单页正文封顶到 budget 字符。
|
|
@@ -107,18 +147,21 @@ def _make_spider(
|
|
|
107
147
|
crawl_id: str,
|
|
108
148
|
state: dict[str, Any],
|
|
109
149
|
domains: set[str],
|
|
150
|
+
policy: dict[str, Any],
|
|
110
151
|
) -> Any:
|
|
111
152
|
"""动态造一个 spider 类。
|
|
112
153
|
|
|
113
154
|
Spider 的 ``start_urls`` / ``allowed_domains`` / ``max_pages`` / ``output_dir``
|
|
114
155
|
都是**类属性**而不是 ``__init__`` 参数 —— ``Spider.__init__`` 只收 crawldir 与
|
|
115
|
-
interval,当构造参数传会直接 TypeError
|
|
156
|
+
interval,当构造参数传会直接 TypeError。所以只能在类体上写。待站策略(robots.txt、
|
|
157
|
+
限速、并发、抓取顺序)同理,它们也是 Spider 的类属性。
|
|
116
158
|
|
|
117
159
|
:param url: 起始 URL
|
|
118
160
|
:param limit: 最多爬多少页
|
|
119
161
|
:param crawl_id: 爬虫 id,用于日志
|
|
120
162
|
:param state: 结果槽;爬完写进它
|
|
121
163
|
:param domains: 起始域集合,链接发现与收页复核共用同一份
|
|
164
|
+
:param policy: ``_crawl_policy`` 读出的待站策略
|
|
122
165
|
:returns: spider 实例
|
|
123
166
|
"""
|
|
124
167
|
from scrapling.spiders import SiteToMarkdownSpider
|
|
@@ -131,6 +174,13 @@ def _make_spider(
|
|
|
131
174
|
allowed_domains = domains
|
|
132
175
|
max_pages = limit
|
|
133
176
|
output_dir = None
|
|
177
|
+
# 待站策略。robots_txt_obey 打开后 0.5 会把「取不到 robots.txt」当成禁止爬该域
|
|
178
|
+
# (0.4.15 是放行),所以这一档要么别开,要么确保那台站点的 robots.txt 取得回来。
|
|
179
|
+
robots_txt_obey = policy["obey_robots"]
|
|
180
|
+
download_delay = policy["delay_seconds"]
|
|
181
|
+
concurrent_requests = policy["concurrency"]
|
|
182
|
+
crawl_strategy = policy["strategy"]
|
|
183
|
+
autothrottle_enabled = policy["autothrottle"]
|
|
134
184
|
|
|
135
185
|
def configure_sessions(self, manager: Any) -> None:
|
|
136
186
|
"""把爬虫的会话换成「只跟安全重定向、走配置里那份代理」的那一份。
|
|
@@ -225,7 +275,7 @@ def _make_spider(
|
|
|
225
275
|
)
|
|
226
276
|
return None
|
|
227
277
|
|
|
228
|
-
return Collector()
|
|
278
|
+
return Collector(crawldir=policy["checkpoint_dir"] or None)
|
|
229
279
|
|
|
230
280
|
|
|
231
281
|
def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
@@ -248,6 +298,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
248
298
|
max_content_chars = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
249
299
|
budget_ms = _positive_int(args.get("maxDurationMs"), "maxDurationMs", DEFAULT_MAX_RUNTIME_MS)
|
|
250
300
|
strip_inline_images = _strip_inline_images(args)
|
|
301
|
+
policy = _crawl_policy(args)
|
|
251
302
|
crawl_id = uuid.uuid4().hex[:12]
|
|
252
303
|
state: dict[str, Any] = {
|
|
253
304
|
"error": None,
|
|
@@ -284,7 +335,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
284
335
|
}
|
|
285
336
|
|
|
286
337
|
try:
|
|
287
|
-
spider = _make_spider(url, max_pages, crawl_id, state, domains)
|
|
338
|
+
spider = _make_spider(url, max_pages, crawl_id, state, domains, policy)
|
|
288
339
|
except BaseException as error:
|
|
289
340
|
with _CRAWL_LOCK:
|
|
290
341
|
_CRAWLS.pop(crawl_id, None)
|
|
@@ -370,21 +421,33 @@ def _get_crawl(crawl_id: Any) -> dict[str, Any]:
|
|
|
370
421
|
def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
371
422
|
"""查一个爬虫的状态与已收结果。
|
|
372
423
|
|
|
424
|
+
``since`` 是本轮之前已经读走多少页(按下标,不是 URL)。带上它只回新增的那一段:
|
|
425
|
+
整份 pages 每轮重发,流量是 O(n²),而 `max_content_chars` 的默认预算意味着几十页就能
|
|
426
|
+
凑出一个超过 Host 侧 8 MiB 帧上限的回包 —— 那一帧会被当成坏帧,整个 sidecar 连正在
|
|
427
|
+
跑的会话一起被拆掉。不带时仍回全部(探针与直连调用要的是全量)。
|
|
428
|
+
|
|
373
429
|
:param args: 协议参数
|
|
374
|
-
:returns: {crawlId, running, pages, error, expired}
|
|
430
|
+
:returns: {crawlId, running, pages, total, error, expired}
|
|
375
431
|
"""
|
|
432
|
+
from adapters import AdapterError
|
|
433
|
+
|
|
434
|
+
since = args.get("since", 0)
|
|
435
|
+
if not isinstance(since, int) or isinstance(since, bool) or since < 0:
|
|
436
|
+
raise AdapterError("BAD_ARGS", "since must be a non-negative integer")
|
|
376
437
|
entry = _get_crawl(args.get("crawlId"))
|
|
377
438
|
state: dict[str, Any] = entry["state"]
|
|
378
439
|
# pages 是 spider 线程边跑边 append 的活列表,而回包要经 json.dumps 序列化。
|
|
379
440
|
# 进锁里复制一份:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
380
441
|
with _CRAWL_LOCK:
|
|
381
|
-
|
|
442
|
+
total = len(state["pages"])
|
|
443
|
+
pages = list(state["pages"][since:])
|
|
382
444
|
running = _is_running(entry)
|
|
383
445
|
return {
|
|
384
446
|
"crawlId": entry["crawl_id"],
|
|
385
447
|
# thread 为 None 表示 spider 还在构造中:没跑起来,但也没结束。
|
|
386
448
|
"running": running,
|
|
387
449
|
"pages": pages,
|
|
450
|
+
"total": total,
|
|
388
451
|
"error": state["error"],
|
|
389
452
|
# 截止到点而停的爬虫带这个标记:模型能看出「为什么比 maxPages 少」。
|
|
390
453
|
"expired": state.get("expired") is True,
|
package/py/guard.py
CHANGED
|
@@ -113,19 +113,6 @@ _BYPASS_ENTRIES: tuple[str, ...] = ()
|
|
|
113
113
|
_PROXY_SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
|
|
114
114
|
_BROWSER_PROXY_SCHEMES = ("http", "https", "socks4", "socks5")
|
|
115
115
|
|
|
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
116
|
# 额外的 NAT64 前缀(CIDR 字符串)。IPv6 地址命中其中之一时,会抽出内嵌 IPv4 复判;
|
|
130
117
|
# 运营商自建前缀必须在这里声明,否则藏在 IPv6 里的私网 IPv4 会被当成公网放行。
|
|
131
118
|
EXTRA_NAT64_PREFIXES: tuple[str, ...] = ()
|
|
@@ -338,7 +325,7 @@ def _run_readonly(argv: list[str]) -> str:
|
|
|
338
325
|
timeout=3,
|
|
339
326
|
check=False,
|
|
340
327
|
)
|
|
341
|
-
except
|
|
328
|
+
except OSError, ValueError, subprocess.SubprocessError:
|
|
342
329
|
return ""
|
|
343
330
|
return done.stdout
|
|
344
331
|
|