@jayyuen66/dsh-scrapling 0.1.5 → 0.1.6
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/CHANGELOG.md +47 -6
- package/LICENSE +1 -1
- package/README.md +15 -15
- package/README.zh-CN.md +13 -13
- package/THIRD_PARTY_NOTICES.md +32 -11
- package/bin/dsh-scrapling.mjs +68 -70
- package/client.js +4 -4
- package/host.js +12 -26
- package/package.json +16 -11
- package/py/adapters.py +30 -8
- package/py/bridge.py +88 -18
- package/py/crawl.py +69 -27
- package/py/extraction.py +67 -21
- package/py/guard.py +55 -24
- package/py/media.py +30 -9
- package/py/redact.py +20 -2
- package/py/redis_storage.py +92 -31
- package/py/search.py +9 -2
- package/py/session_page.py +57 -24
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jayyuen66/dsh-scrapling",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Scrapling 网页抓取插件(dsh):静态/浏览器抓取 + CSS/XPath 结构化抽取 + 选择器自愈 + capture_xhr 与会话网络历史 + 登录态存取 + Spider 爬虫,由常驻 Python 进程驱动。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
@@ -15,7 +15,10 @@
|
|
|
15
15
|
"url": "https://github.com/JayYuen666/dsh-scrapling/issues"
|
|
16
16
|
},
|
|
17
17
|
"license": "MIT",
|
|
18
|
-
"author":
|
|
18
|
+
"author": {
|
|
19
|
+
"name": "JayYuen",
|
|
20
|
+
"url": "https://github.com/JayYuen666"
|
|
21
|
+
},
|
|
19
22
|
"repository": {
|
|
20
23
|
"type": "git",
|
|
21
24
|
"url": "git+https://github.com/JayYuen666/dsh-scrapling.git"
|
|
@@ -67,6 +70,7 @@
|
|
|
67
70
|
},
|
|
68
71
|
"dependencies": {
|
|
69
72
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
73
|
+
"fs-native-extensions": "1.5.3",
|
|
70
74
|
"ipaddr.js": "2.5.0",
|
|
71
75
|
"zod": "4.6.7"
|
|
72
76
|
},
|
|
@@ -106,13 +110,14 @@
|
|
|
106
110
|
"@deepseek-ai/dsh-web": "0.2.2-alpha.2",
|
|
107
111
|
"@deepseek-ai/schemastery": "3.18.6-alpha.1",
|
|
108
112
|
"@e18e/eslint-plugin": "0.8.1",
|
|
109
|
-
"@jayyuen66/dsh-plugin-shared": "0.2.
|
|
113
|
+
"@jayyuen66/dsh-plugin-shared": "0.2.2",
|
|
110
114
|
"@types/node": "26.6.6",
|
|
111
115
|
"@types/react": "19.3.0",
|
|
112
116
|
"@vitest/coverage-v8": "5.0.5",
|
|
113
117
|
"eslint-plugin-regexp": "3.3.2",
|
|
114
118
|
"eslint-plugin-sonarjs": "4.2.2",
|
|
115
119
|
"eslint-plugin-zod": "5.2.2",
|
|
120
|
+
"fast-check": "4.10.2",
|
|
116
121
|
"oxfmt": "0.75.0",
|
|
117
122
|
"oxlint": "1.90.0",
|
|
118
123
|
"oxlint-tsgolint": "7.0.2005",
|
|
@@ -123,12 +128,12 @@
|
|
|
123
128
|
"vitest": "5.0.5"
|
|
124
129
|
},
|
|
125
130
|
"peerDependencies": {
|
|
126
|
-
"@deepseek-ai/dsh": "^0.2.1-rc.3
|
|
127
|
-
"@deepseek-ai/dsh-output-retention": "^0.2.1-rc.3
|
|
128
|
-
"@deepseek-ai/dsh-tools": "^0.2.1-rc.3
|
|
129
|
-
"@deepseek-ai/dsh-typert-protocol": "^0.2.1-rc.3
|
|
130
|
-
"@deepseek-ai/dsh-web": "^0.2.1-rc.3
|
|
131
|
-
"@deepseek-ai/schemastery": "3.18.6-alpha.1"
|
|
131
|
+
"@deepseek-ai/dsh": "^0.2.1-rc.3",
|
|
132
|
+
"@deepseek-ai/dsh-output-retention": "^0.2.1-rc.3",
|
|
133
|
+
"@deepseek-ai/dsh-tools": "^0.2.1-rc.3",
|
|
134
|
+
"@deepseek-ai/dsh-typert-protocol": "^0.2.1-rc.3",
|
|
135
|
+
"@deepseek-ai/dsh-web": "^0.2.1-rc.3",
|
|
136
|
+
"@deepseek-ai/schemastery": "^3.18.6-alpha.1"
|
|
132
137
|
},
|
|
133
138
|
"peerDependenciesMeta": {
|
|
134
139
|
"@deepseek-ai/dsh": {
|
|
@@ -141,7 +146,7 @@
|
|
|
141
146
|
"icon": "icon.svg",
|
|
142
147
|
"engines": {
|
|
143
148
|
"dsh": "^0.2.1-rc.3",
|
|
144
|
-
"node": ">=22.
|
|
149
|
+
"node": ">=22.18.0"
|
|
145
150
|
},
|
|
146
151
|
"dsh": {
|
|
147
152
|
"manifestVersion": 1,
|
|
@@ -173,7 +178,7 @@
|
|
|
173
178
|
"cov:py": "node py-launcher.mjs -m coverage erase && node py-launcher.mjs --env=DSH_PY_COVERAGE=1 -m coverage run --parallel-mode py/tests/test_bridge.py && node py-launcher.mjs -m coverage combine && node py-launcher.mjs -m coverage report -m && node py-launcher.mjs -m coverage erase",
|
|
174
179
|
"coverage:floor": "node py-launcher.mjs -m coverage erase && node py-launcher.mjs --env=DSH_PY_COVERAGE=1 -m coverage run --parallel-mode py/tests/test_bridge.py && node py-launcher.mjs -m coverage combine && node py-launcher.mjs -m coverage report --omit=\"py/tests/*\" --fail-under=74 && node -e \"require('node:fs').mkdirSync('coverage',{recursive:true})\" && node py-launcher.mjs -m coverage json --omit=\"py/tests/*\" -o coverage/python-coverage.json && node coverage-floor.mjs && node py-launcher.mjs -m coverage erase",
|
|
175
180
|
"deps:py": "node deps-check.mjs",
|
|
176
|
-
"check:py": "npm run --loglevel=warn py:which && npm run --loglevel=warn face:py && npm run --loglevel=warn deps:py && npm run --loglevel=warn lint:py && npm run --loglevel=warn fmt:py && npm run --loglevel=warn typecheck:py && npm run --loglevel=warn
|
|
181
|
+
"check:py": "npm run --loglevel=warn py:which && npm run --loglevel=warn face:py && npm run --loglevel=warn deps:py && npm run --loglevel=warn lint:py && npm run --loglevel=warn fmt:py && npm run --loglevel=warn typecheck:py && npm run --loglevel=warn bandit:py && npm run --loglevel=warn coverage:floor",
|
|
177
182
|
"build:cli": "node build-cli.ts"
|
|
178
183
|
}
|
|
179
184
|
}
|
package/py/adapters.py
CHANGED
|
@@ -203,7 +203,7 @@ def _network_summary(
|
|
|
203
203
|
"id": int(meta.get("network_id") or 0),
|
|
204
204
|
"url": redact_url_secrets(str(item.url)),
|
|
205
205
|
"status": item.status,
|
|
206
|
-
"bytes": len(body),
|
|
206
|
+
"bytes": len(body) if body else 0,
|
|
207
207
|
# 上游把方法记在 Response.method 上;从 meta / request_headers 读会退化成 GET,
|
|
208
208
|
# POST 的 XHR 在摘要里一律显示成 GET(V5 已复现)。
|
|
209
209
|
"method": str(getattr(item, "method", "GET")),
|
|
@@ -263,6 +263,9 @@ def _sanitized_page(response: Any, *, main_content_only: bool) -> Any:
|
|
|
263
263
|
return Convertor._sanitize_for_ai(Convertor._strip_noise_tags(page))
|
|
264
264
|
|
|
265
265
|
|
|
266
|
+
_ACTIVE_CONTENT_WARNED = threading.Event()
|
|
267
|
+
|
|
268
|
+
|
|
266
269
|
def _strip_active_content(page: Any) -> None:
|
|
267
270
|
"""剥掉元素上的可执行残留,让清洗后的 HTML 真的只剩内容。
|
|
268
271
|
|
|
@@ -270,9 +273,19 @@ def _strip_active_content(page: Any) -> None:
|
|
|
270
273
|
清洗后 ``onclick`` 照样在,``<meta http-equiv=refresh>`` 与 ``srcdoc`` 也照样在 ——
|
|
271
274
|
那些是事件处理器与跳转指令,直接把内网地址带进模型上下文。html 那条路径还回传
|
|
272
275
|
完整标签,所以得在这里补一刀;text 路径取的是文本,不受属性影响。
|
|
276
|
+
|
|
277
|
+
拿不到可迭的 ``_root`` 时不能静默放行:那意味着上游的树形态变了,本函数从「补一刀」
|
|
278
|
+
退化成「什么都不做」。每个进程只报一次,避免逐条抽取刷屏。
|
|
273
279
|
"""
|
|
274
280
|
root = getattr(page, "_root", None)
|
|
275
281
|
if root is None or not hasattr(root, "iter"):
|
|
282
|
+
if not _ACTIVE_CONTENT_WARNED.is_set():
|
|
283
|
+
_ACTIVE_CONTENT_WARNED.set()
|
|
284
|
+
print(
|
|
285
|
+
"[adapters] page._root has no iter(); active-content attributes were not stripped",
|
|
286
|
+
file=sys.stderr,
|
|
287
|
+
flush=True,
|
|
288
|
+
)
|
|
276
289
|
return
|
|
277
290
|
for element in list(root.iter()):
|
|
278
291
|
tag = str(getattr(element, "tag", "") or "").lower()
|
|
@@ -299,7 +312,7 @@ def _strip_active_content(page: Any) -> None:
|
|
|
299
312
|
# (百分号编码形式则多出 %),两者都不含右括号,所以这个非贪婪匹配不会提前截断。
|
|
300
313
|
_MD_DATA_IMAGE = re.compile(r"!\[([^\]]*)\]\(\s*data:[^)]*\)", re.IGNORECASE)
|
|
301
314
|
# HTML 路径:<img src="data:..."> 与 <source srcset="data:...">。
|
|
302
|
-
_HTML_DATA_ATTR = re.compile(r"""(data:[^"'\s>]+)""", re.IGNORECASE)
|
|
315
|
+
_HTML_DATA_ATTR = re.compile(r"""(data:image/[^"'\s>]+)""", re.IGNORECASE)
|
|
303
316
|
# 代码围栏的分隔行。围栏**内部**的 data URI 必须原样保留 —— 那可能是教程里教的示例代码,
|
|
304
317
|
# 剥掉它等于把文档本身改了。
|
|
305
318
|
_FENCE = re.compile(r"\A\s*(?:```|~~~)")
|
|
@@ -1738,7 +1751,8 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1738
1751
|
:returns: 归一后的载荷
|
|
1739
1752
|
:raises AdapterError: 会话不存在 / 类型不支持 / 抓取失败 / 把 static 专属的键给了浏览器会话
|
|
1740
1753
|
"""
|
|
1741
|
-
|
|
1754
|
+
session_id = args.get("sessionId")
|
|
1755
|
+
entry = _get_session(session_id)
|
|
1742
1756
|
session = entry["session"]
|
|
1743
1757
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1744
1758
|
url = _url(args)
|
|
@@ -1753,19 +1767,24 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1753
1767
|
try:
|
|
1754
1768
|
if entry["type"] == "static":
|
|
1755
1769
|
with entry["lock"]:
|
|
1770
|
+
# 取到条目之后、拿到锁之前,close 可能已经把它摘下并关掉了。未置位时
|
|
1771
|
+
# 会持锁使用一份已关闭的会话,异常最终被归成 FETCH_FAILED——语义错位。
|
|
1772
|
+
if entry.get("closed") is True:
|
|
1773
|
+
raise AdapterError("NO_SUCH_SESSION", f"no such session: {session_id}")
|
|
1756
1774
|
# 与一次性 fetch 同一条复判:static 会话的请求不经过浏览器的 page.route,
|
|
1757
1775
|
# 少了这一道,「Host 判完 → curl_cffi 自己再解析」之间就是敞开的。
|
|
1758
1776
|
allowed, reason = guard.url_allowed(url)
|
|
1759
1777
|
if not allowed:
|
|
1760
1778
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
1761
|
-
# form/json
|
|
1762
|
-
#
|
|
1763
|
-
|
|
1764
|
-
|
|
1779
|
+
# 方法与一次性 fetch 同源:显式 method 优先,没给时由 form/json/body
|
|
1780
|
+
# 推 POST,显式 GET 带体会报错。只看 form/json 的两行写法会让
|
|
1781
|
+
# session.fetch 的 method=PUT/DELETE 与裸 body 静默落地(请求照发、
|
|
1782
|
+
# 语义错了),而调用方从回包上看不出这件事。
|
|
1783
|
+
static_method = _static_method(args)
|
|
1765
1784
|
if static_method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
1766
1785
|
raise AdapterError(
|
|
1767
1786
|
"WRITE_DISABLED",
|
|
1768
|
-
"
|
|
1787
|
+
f"{static_method} changes state on the remote side; the deployment must set "
|
|
1769
1788
|
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
1770
1789
|
)
|
|
1771
1790
|
static_params = _static_params(args, url)
|
|
@@ -2042,6 +2061,9 @@ def _close_entry(session_id: Any) -> None:
|
|
|
2042
2061
|
# 写在锁外会留下这个时序 —— 这里已 pop 并释放锁,构造方接着在锁内读到 False
|
|
2043
2062
|
# 并把建好的会话登记回 _SESSIONS,之后才轮到写 True,那条会话就没人关了。
|
|
2044
2063
|
entry["closed_while_pending"] = True
|
|
2064
|
+
elif entry is not None:
|
|
2065
|
+
# 已构造好的条目:置位与摘除同一临界区,之后抢到 entry 锁的 fetch 会看到它。
|
|
2066
|
+
entry["closed"] = True
|
|
2045
2067
|
if entry is None:
|
|
2046
2068
|
return
|
|
2047
2069
|
if entry.get("pending") is True:
|
package/py/bridge.py
CHANGED
|
@@ -22,8 +22,9 @@
|
|
|
22
22
|
1. **stdout 只能是协议帧。** 任何 ``print`` 或第三方库的进度输出都会把 JSON-lines
|
|
23
23
|
流打坏,所以本文件与 adapters 的一切日志都走 stderr。
|
|
24
24
|
2. **一行一帧且不能交错。** 并发请求各自回帧时要串行化,否则两个响应会被拼在同一行。
|
|
25
|
-
3. **读 stdin 要按字节自行切行。**
|
|
26
|
-
|
|
25
|
+
3. **读 stdin 要按字节自行切行。** 逐帧读取既不能等 ``read(n)`` 读满(管道上会一直
|
|
26
|
+
空等),也不能让 ``readline()`` 把整行先吃进内存(超长残帧会先占住无界缓冲);
|
|
27
|
+
因此按块取字节、在自建的缓冲区里切行并增量判长。
|
|
27
28
|
4. **worker 数与并发上限一致。** 浏览器抓取很吃内存(每个 Chromium 实例数百 MB),
|
|
28
29
|
无上限会让几个并行的工具调用把机器拖垮。
|
|
29
30
|
|
|
@@ -40,7 +41,8 @@ import sys
|
|
|
40
41
|
import threading
|
|
41
42
|
import time
|
|
42
43
|
import traceback
|
|
43
|
-
from
|
|
44
|
+
from io import BufferedReader
|
|
45
|
+
from typing import Any, Callable, cast
|
|
44
46
|
|
|
45
47
|
# 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
|
|
46
48
|
# 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
|
|
@@ -94,8 +96,9 @@ PROTOCOL_VERSION = 1
|
|
|
94
96
|
# 并发上限:与工作线程数一致,多了也只是排队。
|
|
95
97
|
MAX_INFLIGHT = 4
|
|
96
98
|
|
|
97
|
-
#
|
|
98
|
-
#
|
|
99
|
+
# 单帧字节上限。切出整行后先判长度再解析:解析本身就要把这行再展开一份。
|
|
100
|
+
# 读侧按块累积,一旦缓冲超过上限就弃帧报 BAD_FRAME,不会为一个不带换行的写入
|
|
101
|
+
# 继续累积。宿主侧对每个工具的输出另有封顶,这条防的是「入参本身很大」。
|
|
99
102
|
MAX_FRAME_BYTES = 8 * 1024 * 1024
|
|
100
103
|
|
|
101
104
|
# 待处理队列的深度上限。队列只在 worker 全部占满时增长,而 worker 数是 MAX_INFLIGHT,
|
|
@@ -152,6 +155,25 @@ def fail(request_id: Any, code: str, message: str, details: dict[str, Any] | Non
|
|
|
152
155
|
return {"id": request_id, "ok": False, "error": error}
|
|
153
156
|
|
|
154
157
|
|
|
158
|
+
# scrapling 的可选 extra(fetchers / rag)会按需导入这些包;只有它们缺失才算
|
|
159
|
+
# 「环境没装对」。其它 ModuleNotFoundError 是本插件自己的导入缺陷,不能包装成
|
|
160
|
+
# 安装提示——用户照提示装完仍然会失败。
|
|
161
|
+
OPTIONAL_DEPENDENCIES = frozenset(
|
|
162
|
+
{
|
|
163
|
+
"markdownify",
|
|
164
|
+
"playwright",
|
|
165
|
+
"patchright",
|
|
166
|
+
"curl_cffi",
|
|
167
|
+
"browserforge",
|
|
168
|
+
"msgspec",
|
|
169
|
+
"protego",
|
|
170
|
+
"anyio",
|
|
171
|
+
"click",
|
|
172
|
+
"apify_fingerprint_datapoints",
|
|
173
|
+
}
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
155
177
|
def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
156
178
|
"""分发一个请求帧。
|
|
157
179
|
|
|
@@ -184,7 +206,16 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
|
184
206
|
# 而模型与用户对这两种情况的正确反应完全不同:前者该退避重试,后者该去装包。
|
|
185
207
|
# 报错必须指向后者,所以单列一个码,并把本插件的硬性安装命令直接写进去——
|
|
186
208
|
# Scrapling 自己只说「装 markdownify」,而本插件要的是整个 extra。
|
|
187
|
-
missing = error.name or "
|
|
209
|
+
missing = error.name or "某个模块"
|
|
210
|
+
if missing not in OPTIONAL_DEPENDENCIES:
|
|
211
|
+
# 插件自身代码里的导入错误同样会抛 ModuleNotFoundError;把它说成
|
|
212
|
+
# 「去装 rag extra」会让用户装完仍然报同一个错。
|
|
213
|
+
log(f"{method} aborted: internal import failed: {missing}")
|
|
214
|
+
return fail(
|
|
215
|
+
request_id,
|
|
216
|
+
"FETCH_FAILED",
|
|
217
|
+
f"内部依赖导入失败:{missing}(这是插件自身的缺陷,不是环境缺包)",
|
|
218
|
+
)
|
|
188
219
|
log(f"{method} aborted: missing dependency {missing}")
|
|
189
220
|
return fail(
|
|
190
221
|
request_id,
|
|
@@ -233,7 +264,15 @@ def _worker() -> None:
|
|
|
233
264
|
try:
|
|
234
265
|
emit(handle(frame))
|
|
235
266
|
except Exception as error: # noqa: BLE001 —— 连序列化失败都不能让线程死掉
|
|
236
|
-
|
|
267
|
+
request_id = frame.get("id")
|
|
268
|
+
log(f"emit failed for request {request_id}: {type(error).__name__}: {error}")
|
|
269
|
+
try:
|
|
270
|
+
emit(fail(request_id, "INTERNAL", f"failed to emit response: {type(error).__name__}: {error}"))
|
|
271
|
+
except Exception as fallback_error: # noqa: BLE001 —— 兜底帧也写不出去,只能留日志
|
|
272
|
+
log(
|
|
273
|
+
f"fallback frame for request {request_id} also failed: "
|
|
274
|
+
f"{type(fallback_error).__name__}: {fallback_error}"
|
|
275
|
+
)
|
|
237
276
|
finally:
|
|
238
277
|
with _WORKERS_LOCK:
|
|
239
278
|
current = threading.current_thread()
|
|
@@ -281,9 +320,9 @@ def _shutdown_sessions() -> None:
|
|
|
281
320
|
|
|
282
321
|
浏览器会话是独立进程:sidecar 自己退了、Chromium 还活着,就成了没人管的孤儿。
|
|
283
322
|
"""
|
|
284
|
-
import adapters
|
|
285
|
-
|
|
286
323
|
try:
|
|
324
|
+
import adapters
|
|
325
|
+
|
|
287
326
|
adapters.close_all_sessions()
|
|
288
327
|
except Exception as error: # noqa: BLE001 —— 关不掉也不能拖住关机
|
|
289
328
|
log(f"failed to close sessions: {type(error).__name__}: {error}")
|
|
@@ -331,14 +370,23 @@ def read_loop() -> int:
|
|
|
331
370
|
except Exception as error: # noqa: BLE001
|
|
332
371
|
log(f"failed to report readiness: {type(error).__name__}: {error}")
|
|
333
372
|
|
|
334
|
-
#
|
|
373
|
+
# 必须按块读(read1),既不能用 read(65536),也不能用 readline()。
|
|
335
374
|
# BufferedReader.read(n) 的语义是「读满 n 字节或遇到 EOF」:宿主只要保持管道开着
|
|
336
375
|
# (而常驻进程本来就该一直开着),它就会一直等下去,第一个请求永远进不来。
|
|
337
376
|
# 实测踩过:批量发完立刻 close stdin 的探针能过,逐帧交互的客户端会挂死。
|
|
338
|
-
# readline()
|
|
339
|
-
|
|
377
|
+
# readline() 则把整行读进内存**才**交回来:宿主侧 FrameSplitter 在
|
|
378
|
+
# MAX_FRAME_BYTES 处增量截断,这里若等整行,一个不带换行的超长写入仍会把无界字节
|
|
379
|
+
# 吃进内存(两侧同解的对称性缺口)。read1 有多少给多少,配合自建的 pending
|
|
380
|
+
# 增量判长,超限即弃帧报 BAD_FRAME 并清到下一行。
|
|
381
|
+
# typeshed 把 sys.stdin.buffer 标成 BinaryIO,那份协议里没有 read1;运行时它是
|
|
382
|
+
# _io.BufferedReader(管道与重定向文件都实测到这一型),cast 补这处过粗的标注。
|
|
383
|
+
stream = cast(BufferedReader, sys.stdin.buffer)
|
|
384
|
+
pending = bytearray()
|
|
385
|
+
|
|
386
|
+
def handle_raw(raw: bytes) -> bool:
|
|
387
|
+
"""处理一个完整帧(含行尾换行)。交回 False = 收到 shutdown,读循环退出。"""
|
|
340
388
|
if not raw.strip():
|
|
341
|
-
|
|
389
|
+
return True
|
|
342
390
|
if len(raw) > MAX_FRAME_BYTES:
|
|
343
391
|
emit(
|
|
344
392
|
fail(
|
|
@@ -347,15 +395,15 @@ def read_loop() -> int:
|
|
|
347
395
|
f"frame of {len(raw)} bytes exceeds the {MAX_FRAME_BYTES} byte limit",
|
|
348
396
|
)
|
|
349
397
|
)
|
|
350
|
-
|
|
398
|
+
return True
|
|
351
399
|
try:
|
|
352
400
|
frame = json.loads(raw.decode("utf-8"))
|
|
353
401
|
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
354
402
|
emit(fail(None, "BAD_FRAME", f"unparsable frame: {error}"))
|
|
355
|
-
|
|
403
|
+
return True
|
|
356
404
|
if not isinstance(frame, dict):
|
|
357
405
|
emit(fail(None, "BAD_FRAME", "frame must be an object"))
|
|
358
|
-
|
|
406
|
+
return True
|
|
359
407
|
if frame.get("method") == "shutdown":
|
|
360
408
|
emit(ok(frame.get("id"), {"stopping": True}))
|
|
361
409
|
_drain_before_exit()
|
|
@@ -363,7 +411,7 @@ def read_loop() -> int:
|
|
|
363
411
|
# 本身。宿主的优雅关闭走的就是这一帧(见 lib/sidecar.ts 的 dispose)。
|
|
364
412
|
_shutdown_crawls()
|
|
365
413
|
_shutdown_sessions()
|
|
366
|
-
return
|
|
414
|
+
return False
|
|
367
415
|
# 顺序要紧:先入队再起 worker。反过来的话,新起的线程可能立刻醒来、
|
|
368
416
|
# 看到空队列就退出,这一帧就永远没人处理 —— 且只在时序凑巧时才会复现。
|
|
369
417
|
busy_reply: dict[str, Any] | None = None
|
|
@@ -382,8 +430,30 @@ def read_loop() -> int:
|
|
|
382
430
|
# emit 在锁外:stdout 一旦阻塞(宿主读得慢),持锁写流会把全部 worker 的
|
|
383
431
|
# _drain 一起冻住 —— 回帧可以慢,队列不能停。
|
|
384
432
|
emit(busy_reply)
|
|
385
|
-
|
|
433
|
+
return True
|
|
386
434
|
_ensure_worker(min(depth, MAX_INFLIGHT))
|
|
435
|
+
return True
|
|
436
|
+
|
|
437
|
+
for chunk in iter(lambda: stream.read1(65536), b""):
|
|
438
|
+
pending.extend(chunk)
|
|
439
|
+
while b"\n" in pending:
|
|
440
|
+
index = pending.index(b"\n")
|
|
441
|
+
raw = bytes(pending[: index + 1])
|
|
442
|
+
del pending[: index + 1]
|
|
443
|
+
if not handle_raw(raw):
|
|
444
|
+
log("stdin closed")
|
|
445
|
+
return 0
|
|
446
|
+
if len(pending) > MAX_FRAME_BYTES:
|
|
447
|
+
# 无换行的超长残帧:与宿主侧 FrameSplitter 同解——弃缓冲、报 BAD_FRAME、
|
|
448
|
+
# 进程不死,后续带换行的合法帧照常处理。
|
|
449
|
+
del pending[:]
|
|
450
|
+
emit(
|
|
451
|
+
fail(
|
|
452
|
+
None,
|
|
453
|
+
"BAD_FRAME",
|
|
454
|
+
f"a frame went over the {MAX_FRAME_BYTES} byte limit without a newline",
|
|
455
|
+
)
|
|
456
|
+
)
|
|
387
457
|
log("stdin closed")
|
|
388
458
|
_drain_before_exit()
|
|
389
459
|
_shutdown_crawls()
|
package/py/crawl.py
CHANGED
|
@@ -151,7 +151,9 @@ def _allowed_domains(url: str) -> set[str]:
|
|
|
151
151
|
# 主机名与 host:port 都放进去:Scrapling 的域过滤可能按 hostname 比,也可能按
|
|
152
152
|
# netloc 比。少放一个的表现是「只爬到第一页就停」,不报错,很难一眼看出原因。
|
|
153
153
|
parsed = urlparse(url)
|
|
154
|
-
|
|
154
|
+
# 统一小写:_within_allowed_domains 拿 netloc.lower() 来比,集合里保留原大小写
|
|
155
|
+
# 会让 `http://Example.com:8080/` 的每一页都判成站外(只抓到 0 页且不报错)。
|
|
156
|
+
return {value.lower() for value in (parsed.hostname, parsed.netloc) if value}
|
|
155
157
|
|
|
156
158
|
|
|
157
159
|
def _within_allowed_domains(url: str, allowed: set[str]) -> bool:
|
|
@@ -282,17 +284,6 @@ def _session_config(manager: Any, url: str) -> None:
|
|
|
282
284
|
manager.add("default", FetcherSession(**session_kwargs))
|
|
283
285
|
|
|
284
286
|
|
|
285
|
-
def _policy_attrs(policy: dict[str, Any]) -> dict[str, Any]:
|
|
286
|
-
"""Spider 类属性上的待站策略(三种模板共用同一份)。"""
|
|
287
|
-
return {
|
|
288
|
-
"robots_txt_obey": policy["obey_robots"],
|
|
289
|
-
"download_delay": policy["delay_seconds"],
|
|
290
|
-
"concurrent_requests": policy["concurrency"],
|
|
291
|
-
"crawl_strategy": policy["strategy"],
|
|
292
|
-
"autothrottle_enabled": policy["autothrottle"],
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
287
|
def _make_spider(
|
|
297
288
|
url: str,
|
|
298
289
|
limit: int,
|
|
@@ -751,7 +742,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
751
742
|
# shopify 模式真正抓的主机可以来自 sitemapUrl:_make_shopify_spider 用它的 netloc 拼
|
|
752
743
|
# collections/products 两个 URL。而站内判定用的是 allowed_domains —— 两处取不同来源时
|
|
753
744
|
# spider 发出的每个请求都会被判成站外,一页都收不到。所以主机以真正要打的那一个为准。
|
|
754
|
-
domain_source =
|
|
745
|
+
domain_source = _domain_source_of(mode, url, sitemap_url, feed_url)
|
|
755
746
|
domains = _allowed_domains(domain_source)
|
|
756
747
|
|
|
757
748
|
# Host 闸门判的是这条 URL,但协议层不该假设调用方一定判过:这道复核与浏览器路径上
|
|
@@ -847,7 +838,7 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
847
838
|
"exclude_patterns": exclude_patterns,
|
|
848
839
|
},
|
|
849
840
|
)
|
|
850
|
-
except
|
|
841
|
+
except Exception as error:
|
|
851
842
|
with _CRAWL_LOCK:
|
|
852
843
|
_CRAWLS.pop(crawl_id, None)
|
|
853
844
|
if isinstance(error, AdapterError):
|
|
@@ -875,12 +866,8 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
875
866
|
# crawlStarted 必须在 start() **之前**发。反过来有两处会出错:一是快蜘蛛可能在这一帧落地
|
|
876
867
|
# 之前就先推了 progress,宿主侧「第一条是 crawlStarted」的读法于是变成随缘;二是万一这一帧
|
|
877
868
|
# 发不出去(stdout 断了、序列化炸了),异常抛给调用方时蜘蛛已经在跑 —— 调用方拿不到
|
|
878
|
-
# crawlId
|
|
879
|
-
|
|
880
|
-
"crawlStarted",
|
|
881
|
-
crawlId=crawl_id,
|
|
882
|
-
text=f"crawling {url} in {mode} mode (max {max_pages} items)",
|
|
883
|
-
)
|
|
869
|
+
# crawlId,就叫不停它,那个名额要一直占到进程退出。撤占位与重抛在 _announce_crawl_started 里。
|
|
870
|
+
_announce_crawl_started(crawl_id, f"crawling {url} in {mode} mode (max {max_pages} items)")
|
|
884
871
|
try:
|
|
885
872
|
thread.start()
|
|
886
873
|
except RuntimeError:
|
|
@@ -891,6 +878,25 @@ def crawl_run(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
891
878
|
return {"crawlId": crawl_id}
|
|
892
879
|
|
|
893
880
|
|
|
881
|
+
def _announce_crawl_started(crawl_id: str, message: str) -> None:
|
|
882
|
+
"""发 crawlStarted 帧;发不出去就撤掉占位再抛。
|
|
883
|
+
|
|
884
|
+
调用方此时已经登记了 spider 与 thread,但还没 start()。这一帧发不出去(stdout
|
|
885
|
+
断了、序列化炸了)时异常要抛给调用方,登记也必须撤掉:调用方拿不到 crawlId
|
|
886
|
+
就叫不停这条爬虫,留着的登记会被 _is_running 当成「正在跑」,名额一直占到
|
|
887
|
+
进程退出。
|
|
888
|
+
|
|
889
|
+
:param crawl_id: 爬虫登记键
|
|
890
|
+
:param message: 帧正文
|
|
891
|
+
"""
|
|
892
|
+
try:
|
|
893
|
+
_emit_event("crawlStarted", crawlId=crawl_id, text=message)
|
|
894
|
+
except BaseException:
|
|
895
|
+
with _CRAWL_LOCK:
|
|
896
|
+
_CRAWLS.pop(crawl_id, None)
|
|
897
|
+
raise
|
|
898
|
+
|
|
899
|
+
|
|
894
900
|
def _is_running(entry: dict[str, Any]) -> bool:
|
|
895
901
|
"""这个登记条目算不算「正在跑」。
|
|
896
902
|
|
|
@@ -940,6 +946,24 @@ def _get_crawl(crawl_id: Any) -> dict[str, Any]:
|
|
|
940
946
|
return entry
|
|
941
947
|
|
|
942
948
|
|
|
949
|
+
def _domain_source_of(
|
|
950
|
+
mode: str,
|
|
951
|
+
url: str,
|
|
952
|
+
sitemap_url: str | None,
|
|
953
|
+
feed_url: str | None,
|
|
954
|
+
) -> str:
|
|
955
|
+
"""真正被 spider 请求的那个地址:站内判定以它的主机为准。
|
|
956
|
+
|
|
957
|
+
sitemap / shopify 抓的是 sitemapUrl,feed 抓的是 feedUrl;起点 url 只决定默认值。
|
|
958
|
+
两处取不同来源时,spider 发出的每个请求都会被引擎判成站外。
|
|
959
|
+
"""
|
|
960
|
+
if mode in ("shopify", "sitemap"):
|
|
961
|
+
return sitemap_url or url
|
|
962
|
+
if mode == "feed":
|
|
963
|
+
return feed_url or url
|
|
964
|
+
return url
|
|
965
|
+
|
|
966
|
+
|
|
943
967
|
def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
944
968
|
"""查一个爬虫的状态与已收结果。
|
|
945
969
|
|
|
@@ -963,10 +987,12 @@ def crawl_status(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
963
987
|
# 进锁里取一段:一边序列化一边追加,结果要么漏一页要么撞上 RuntimeError。
|
|
964
988
|
with _CRAWL_LOCK:
|
|
965
989
|
feed_rows = state.get("mode") in ("feed", "shopify")
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
990
|
+
# 锁内只取稳定快照:序列化计量与截断是纯 CPU 工作,放进全局锁会把所有
|
|
991
|
+
# worker 的 crawl.run / stop / close_all_crawls 串行化到回包速度上。
|
|
992
|
+
source = list(state["rows"] if feed_rows else state["pages"])
|
|
969
993
|
running = _is_running(entry)
|
|
994
|
+
total = len(source)
|
|
995
|
+
taken, more = _take_pages(source, since)
|
|
970
996
|
pages = [] if feed_rows else taken
|
|
971
997
|
rows = taken if feed_rows else []
|
|
972
998
|
return {
|
|
@@ -1006,7 +1032,19 @@ def _shrink_page(page: dict[str, Any], budget: int) -> dict[str, Any]:
|
|
|
1006
1032
|
:returns: 压过的新页(不就地改原对象,state 里留全量)
|
|
1007
1033
|
"""
|
|
1008
1034
|
if "markdown" not in page:
|
|
1009
|
-
|
|
1035
|
+
# feed/shopify 的行没有 markdown:退化成「反复把最长的字符串字段减半」。
|
|
1036
|
+
# 不处理这一类,超大的行仍会顶过 Host 的 8 MiB 切帧线。
|
|
1037
|
+
shrunk = dict(page)
|
|
1038
|
+
while len(json.dumps(shrunk, ensure_ascii=False).encode("utf-8")) > budget:
|
|
1039
|
+
key = max(
|
|
1040
|
+
(name for name, value in shrunk.items() if isinstance(value, str) and value),
|
|
1041
|
+
key=lambda name: len(shrunk[name]),
|
|
1042
|
+
default=None,
|
|
1043
|
+
)
|
|
1044
|
+
if key is None:
|
|
1045
|
+
break
|
|
1046
|
+
shrunk[key] = shrunk[key][: len(shrunk[key]) // 2]
|
|
1047
|
+
return {**shrunk, "truncated": True}
|
|
1010
1048
|
overhead = len(json.dumps({**page, "markdown": ""}, ensure_ascii=False).encode("utf-8"))
|
|
1011
1049
|
room = max(0, budget - overhead)
|
|
1012
1050
|
markdown = str(page.get("markdown", ""))
|
|
@@ -1062,10 +1100,14 @@ def _request_stop(entry: dict[str, Any]) -> bool:
|
|
|
1062
1100
|
state["deadline"] = time.monotonic()
|
|
1063
1101
|
with _CRAWL_LOCK:
|
|
1064
1102
|
spider = entry.get("spider")
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1103
|
+
worker = entry.get("thread")
|
|
1104
|
+
# 线程对象已登记但还没 start()(ident 为 None)也算「还没跑起来」:这段窗口里
|
|
1105
|
+
# 只调 pause 对未启动的引擎无效,worker 起手仍会照常抓取。
|
|
1106
|
+
if spider is None or worker is None or worker.ident is None:
|
|
1068
1107
|
entry["stop_requested"] = True
|
|
1108
|
+
running = False
|
|
1109
|
+
else:
|
|
1110
|
+
running = _is_running(entry)
|
|
1069
1111
|
if spider is not None and running:
|
|
1070
1112
|
with suppress(RuntimeError):
|
|
1071
1113
|
spider.pause()
|