@jayyuen66/dsh-scrapling 0.1.16 → 0.2.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/CHANGELOG.md +73 -0
- package/README.md +160 -251
- package/README.zh-CN.md +226 -317
- package/THIRD_PARTY_NOTICES.md +54 -15
- package/bin/dsh-scrapling.mjs +13 -74
- package/client.js +6 -6
- package/cordis.patch.yml +1 -1
- package/docs/DETAIL.md +22 -22
- package/docs/DETAIL.zh.md +27 -27
- package/docs/images/architecture.svg +100 -0
- package/docs/images/architecture.zh.svg +99 -0
- package/docs/images/tool-selection.svg +88 -0
- package/docs/images/tool-selection.zh.svg +88 -0
- package/host.js +26 -45
- package/package.json +67 -62
- package/py/adapters.py +204 -57
- package/py/bridge.py +80 -8
- package/py/cancellation.py +56 -0
- package/py/crawl.py +1 -1
- package/py/document.py +128 -0
- package/py/documents-requirements.txt +1 -0
- package/py/extraction.py +2 -2
- package/py/media.py +4 -3
- package/py/runtime-requirements.txt +4 -3
- package/py/search.py +109 -24
- package/py/session_page.py +92 -24
- package/runtime-manifest.json +6 -0
package/py/bridge.py
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
协议(Host -> Python,每行一个 JSON 对象)::
|
|
8
8
|
|
|
9
9
|
{"id": "7", "method": "fetch", "params": {...}}
|
|
10
|
+
{"id": "cancel-7", "method": "cancel", "params": {"id": "7"}}
|
|
11
|
+
|
|
12
|
+
取消只设置请求 token;适配器在抓取、读取与动作的安全边界检查,不强行中断阻塞调用。
|
|
10
13
|
|
|
11
14
|
响应(Python -> Host,同样一行一个)::
|
|
12
15
|
|
|
@@ -35,6 +38,7 @@
|
|
|
35
38
|
|
|
36
39
|
from __future__ import annotations
|
|
37
40
|
|
|
41
|
+
import contextlib
|
|
38
42
|
import json
|
|
39
43
|
import os
|
|
40
44
|
import sys
|
|
@@ -42,13 +46,16 @@ import threading
|
|
|
42
46
|
import time
|
|
43
47
|
import traceback
|
|
44
48
|
from io import BufferedReader
|
|
45
|
-
from typing import Any, Callable, cast
|
|
49
|
+
from typing import TYPE_CHECKING, Any, Callable, cast
|
|
50
|
+
|
|
51
|
+
if TYPE_CHECKING:
|
|
52
|
+
from cancellation import CancellationToken
|
|
46
53
|
|
|
47
54
|
# 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
|
|
48
55
|
# 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
|
|
49
56
|
# 也会让它们退成 ascii —— 那时 emit 里的非 ASCII 正文会抛 UnicodeEncodeError,而
|
|
50
57
|
# worker 把它当请求异常吞掉,调用方拿不到任何响应,只能等到超时。
|
|
51
|
-
# backslashreplace
|
|
58
|
+
# backslashreplace 处理另一个方向:json.loads 能把 "\ud800" 解成孤立代理项,严格编码
|
|
52
59
|
# 会让整帧写不出去,替换成转义文本至少留下可读的痕迹。
|
|
53
60
|
# 用 getattr 取 reconfigure:被重定向成 io.StringIO 的流没有这个方法(测试与嵌宿主都可能
|
|
54
61
|
# 这么做),缺了它不该让整个 sidecar 起不来。
|
|
@@ -157,6 +164,8 @@ _QUEUE: list[dict[str, Any]] = []
|
|
|
157
164
|
_QUEUE_LOCK = threading.Lock()
|
|
158
165
|
_WORKERS_LOCK = threading.Lock()
|
|
159
166
|
_WORKERS: list[threading.Thread] = []
|
|
167
|
+
_REQUEST_TOKENS_LOCK = threading.Lock()
|
|
168
|
+
_REQUEST_TOKENS: dict[str, CancellationToken] = {}
|
|
160
169
|
|
|
161
170
|
|
|
162
171
|
def log(message: str) -> None:
|
|
@@ -200,6 +209,41 @@ def fail(request_id: Any, code: str, message: str, details: dict[str, Any] | Non
|
|
|
200
209
|
return {"id": request_id, "ok": False, "error": error}
|
|
201
210
|
|
|
202
211
|
|
|
212
|
+
def _register_request(request_id: Any) -> CancellationToken | None:
|
|
213
|
+
"""为已接收的请求登记 token;排队项也登记,出队后先检查再执行。"""
|
|
214
|
+
from cancellation import CancellationToken
|
|
215
|
+
|
|
216
|
+
if not isinstance(request_id, str):
|
|
217
|
+
return None
|
|
218
|
+
with _REQUEST_TOKENS_LOCK:
|
|
219
|
+
token = _REQUEST_TOKENS.get(request_id)
|
|
220
|
+
if token is None:
|
|
221
|
+
token = CancellationToken()
|
|
222
|
+
_REQUEST_TOKENS[request_id] = token
|
|
223
|
+
return token
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _release_request(request_id: Any, token: CancellationToken | None) -> None:
|
|
227
|
+
"""只摘自己这一笔,避免延迟完成或重复 id 误删后来登记的 token。"""
|
|
228
|
+
if token is None or not isinstance(request_id, str):
|
|
229
|
+
return
|
|
230
|
+
with _REQUEST_TOKENS_LOCK:
|
|
231
|
+
if _REQUEST_TOKENS.get(request_id) is token:
|
|
232
|
+
_REQUEST_TOKENS.pop(request_id, None)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _cancel_request(request_id: Any) -> bool:
|
|
236
|
+
"""设置运行中或排队请求的取消事件;未知、已完成 id 都是 no-op。"""
|
|
237
|
+
if not isinstance(request_id, str):
|
|
238
|
+
return False
|
|
239
|
+
with _REQUEST_TOKENS_LOCK:
|
|
240
|
+
token = _REQUEST_TOKENS.get(request_id)
|
|
241
|
+
if token is None:
|
|
242
|
+
return False
|
|
243
|
+
token.cancel()
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
|
|
203
247
|
# scrapling 的可选 extra(fetchers / rag)会按需导入这些包;只有它们缺失才算
|
|
204
248
|
# 「环境没装对」。其它 ModuleNotFoundError 是本插件自己的导入缺陷,不能包装成
|
|
205
249
|
# 安装提示——用户照提示装完仍然会失败。
|
|
@@ -220,12 +264,26 @@ OPTIONAL_DEPENDENCIES = frozenset(
|
|
|
220
264
|
|
|
221
265
|
|
|
222
266
|
def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
223
|
-
"""
|
|
267
|
+
"""分发一个请求帧,并把取消 token 绑定到这一次 handler 调用。"""
|
|
268
|
+
from cancellation import RequestCancelled, bind, raise_if_cancelled
|
|
224
269
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
270
|
+
request_id = frame.get("id")
|
|
271
|
+
token = _register_request(request_id)
|
|
272
|
+
try:
|
|
273
|
+
with bind(token) if token is not None else contextlib.nullcontext():
|
|
274
|
+
try:
|
|
275
|
+
raise_if_cancelled()
|
|
276
|
+
return _handle_request(frame)
|
|
277
|
+
except RequestCancelled:
|
|
278
|
+
return fail(request_id, "SIDECAR_ABORTED", f"{frame.get('method')} was cancelled")
|
|
279
|
+
finally:
|
|
280
|
+
_release_request(request_id, token)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _handle_request(frame: dict[str, Any]) -> dict[str, Any]:
|
|
284
|
+
"""校验并执行一个已绑定取消上下文的请求。"""
|
|
228
285
|
import adapters
|
|
286
|
+
from cancellation import RequestCancelled, raise_if_cancelled
|
|
229
287
|
|
|
230
288
|
request_id = frame.get("id")
|
|
231
289
|
method = frame.get("method")
|
|
@@ -243,7 +301,11 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
|
|
|
243
301
|
|
|
244
302
|
with _SLOTS:
|
|
245
303
|
try:
|
|
304
|
+
# 等待并发名额期间也可能收到 cancel;拿到名额后再判一次。
|
|
305
|
+
raise_if_cancelled()
|
|
246
306
|
return ok(request_id, handler(params))
|
|
307
|
+
except RequestCancelled:
|
|
308
|
+
raise
|
|
247
309
|
except adapters.AdapterError as error:
|
|
248
310
|
return fail(request_id, error.code, str(error), error.details)
|
|
249
311
|
except ModuleNotFoundError as error:
|
|
@@ -405,7 +467,7 @@ def _drain_before_exit(timeout: float = 5.0) -> None:
|
|
|
405
467
|
|
|
406
468
|
点名只覆盖队列里的帧:已经出队、正在 handler 里跑的请求没有一处集中的登记面,要命名
|
|
407
469
|
它们就得在 worker 的热路径上加簿记,这比一条关机日志不值。那一路的后果由
|
|
408
|
-
`_shutdown_crawls` / `_shutdown_sessions`
|
|
470
|
+
`_shutdown_crawls` / `_shutdown_sessions` 的有界关闭负责清理(宿主侧等的是帧,不是关闭)。
|
|
409
471
|
|
|
410
472
|
:param timeout - 最长等待秒数
|
|
411
473
|
"""
|
|
@@ -451,7 +513,7 @@ def read_loop() -> int:
|
|
|
451
513
|
# 必须按块读(read1),既不能用 read(65536),也不能用 readline()。
|
|
452
514
|
# BufferedReader.read(n) 的语义是「读满 n 字节或遇到 EOF」:宿主只要保持管道开着
|
|
453
515
|
# (而常驻进程本来就该一直开着),它就会一直等下去,第一个请求永远进不来。
|
|
454
|
-
#
|
|
516
|
+
# 批量发完立刻 close stdin 的探针能靠这条语义侥幸通过,逐帧交互的客户端会挂死。
|
|
455
517
|
# readline() 则把整行读进内存**才**交回来:宿主侧 FrameSplitter 在
|
|
456
518
|
# MAX_FRAME_BYTES 处增量截断,这里若等整行,一个不带换行的超长写入仍会把无界字节
|
|
457
519
|
# 吃进内存(两侧同解的对称性缺口)。read1 有多少给多少,配合自建的 pending
|
|
@@ -482,6 +544,15 @@ def read_loop() -> int:
|
|
|
482
544
|
if not isinstance(frame, dict):
|
|
483
545
|
emit(fail(None, "BAD_FRAME", "frame must be an object"))
|
|
484
546
|
return True
|
|
547
|
+
if frame.get("method") == "cancel":
|
|
548
|
+
params = frame.get("params")
|
|
549
|
+
target = params.get("id") if isinstance(params, dict) else None
|
|
550
|
+
if not isinstance(target, str) or not target:
|
|
551
|
+
emit(fail(frame.get("id"), "BAD_ARGS", "cancel requires a non-empty string id"))
|
|
552
|
+
return True
|
|
553
|
+
_cancel_request(target)
|
|
554
|
+
emit(ok(frame.get("id"), {"cancelled": True}))
|
|
555
|
+
return True
|
|
485
556
|
if frame.get("method") == "shutdown":
|
|
486
557
|
emit(ok(frame.get("id"), {"stopping": True}))
|
|
487
558
|
_drain_before_exit()
|
|
@@ -502,6 +573,7 @@ def read_loop() -> int:
|
|
|
502
573
|
f"{depth} requests already queued (limit {MAX_QUEUE_DEPTH})",
|
|
503
574
|
)
|
|
504
575
|
else:
|
|
576
|
+
_register_request(frame.get("id"))
|
|
505
577
|
_QUEUE.append(frame)
|
|
506
578
|
depth += 1
|
|
507
579
|
if busy_reply is not None:
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""逐请求取消 token;只在调用方明确设置的安全阶段边界生效。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from threading import Event
|
|
8
|
+
from typing import Iterator
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RequestCancelled(RuntimeError):
|
|
12
|
+
"""当前请求已被取消;bridge 负责把它映射成协议错误码。"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CancellationToken:
|
|
16
|
+
"""可跨线程设置的请求级取消事件。"""
|
|
17
|
+
|
|
18
|
+
def __init__(self) -> None:
|
|
19
|
+
self._event = Event()
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def cancelled(self) -> bool:
|
|
23
|
+
"""是否已经收到取消。"""
|
|
24
|
+
return self._event.is_set()
|
|
25
|
+
|
|
26
|
+
def cancel(self) -> None:
|
|
27
|
+
"""设置取消事件;重复调用没有副作用。"""
|
|
28
|
+
self._event.set()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_CURRENT_TOKEN: ContextVar[CancellationToken | None] = ContextVar(
|
|
32
|
+
"dsh_scrapling_cancellation",
|
|
33
|
+
default=None,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def current_token() -> CancellationToken | None:
|
|
38
|
+
"""返回当前请求绑定的 token;没有请求上下文时为 None。"""
|
|
39
|
+
return _CURRENT_TOKEN.get()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@contextmanager
|
|
43
|
+
def bind(token: CancellationToken) -> Iterator[None]:
|
|
44
|
+
"""把 token 绑定到当前线程与异步上下文,并在退出时恢复上一层。"""
|
|
45
|
+
previous = _CURRENT_TOKEN.set(token)
|
|
46
|
+
try:
|
|
47
|
+
yield
|
|
48
|
+
finally:
|
|
49
|
+
_CURRENT_TOKEN.reset(previous)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def raise_if_cancelled() -> None:
|
|
53
|
+
"""在安全阶段边界检查取消;不试图中断阻塞中的第三方调用。"""
|
|
54
|
+
token = current_token()
|
|
55
|
+
if token is not None and token.cancelled:
|
|
56
|
+
raise RequestCancelled("request was cancelled")
|
package/py/crawl.py
CHANGED
|
@@ -350,7 +350,7 @@ def _make_spider(
|
|
|
350
350
|
"""把爬虫的会话换成「只跟安全重定向、走配置里那份代理」的那一份。
|
|
351
351
|
|
|
352
352
|
Spider 默认加的是不带参数的 ``FetcherSession()``,重定向按 curl_cffi 的默认走 —— 跳向私网
|
|
353
|
-
不会被拦。Host 闸门只判起点 URL
|
|
353
|
+
不会被拦。Host 闸门只判起点 URL,重定向目标是它看不到的,所以这里必须自己拦:
|
|
354
354
|
``follow_redirects="safe"`` 让 curl_cffi 拒绝跳向私网的跳转。
|
|
355
355
|
|
|
356
356
|
代理按起点 URL 定档(``allowed_domains`` 已经把爬虫锁在起点所在的域里,所以
|
package/py/document.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""PDF 文本读取:流式下载到临时文件,再用可选 pypdf 逐页抽取。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from cancellation import raise_if_cancelled
|
|
10
|
+
|
|
11
|
+
DEFAULT_MAX_BYTES = 20 * 1024 * 1024
|
|
12
|
+
DEFAULT_MAX_PAGES = 200
|
|
13
|
+
DEFAULT_MAX_OUTPUT_CHARS = 200_000
|
|
14
|
+
PYPDF_VERSION = "7.1.1"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def available() -> bool:
|
|
18
|
+
"""pypdf 是否可导入;缺包不影响 sidecar 启动。"""
|
|
19
|
+
try:
|
|
20
|
+
from pypdf import PdfReader
|
|
21
|
+
except ImportError:
|
|
22
|
+
return False
|
|
23
|
+
return callable(PdfReader)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _error(code: str, message: str) -> Exception:
|
|
27
|
+
from adapters import AdapterError
|
|
28
|
+
|
|
29
|
+
return AdapterError(code, message)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _positive(value: Any, field: str, default: int) -> int:
|
|
33
|
+
from adapters import _positive_int
|
|
34
|
+
|
|
35
|
+
return _positive_int(value, field, default)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _limits(args: dict[str, Any]) -> tuple[int, int, int]:
|
|
39
|
+
"""模型上限只能向下收,部署缺省值就是各参数声明的三档默认值。"""
|
|
40
|
+
deployment = args.get("deployment")
|
|
41
|
+
if deployment is None:
|
|
42
|
+
deployment = {}
|
|
43
|
+
if not isinstance(deployment, dict):
|
|
44
|
+
raise _error("BAD_ARGS", "deployment must be an object")
|
|
45
|
+
byte_ceiling = _positive(deployment.get("documentMaxBytes"), "deployment.documentMaxBytes", DEFAULT_MAX_BYTES)
|
|
46
|
+
page_ceiling = _positive(deployment.get("documentMaxPages"), "deployment.documentMaxPages", DEFAULT_MAX_PAGES)
|
|
47
|
+
output_ceiling = _positive(
|
|
48
|
+
deployment.get("documentMaxOutputChars"),
|
|
49
|
+
"deployment.documentMaxOutputChars",
|
|
50
|
+
DEFAULT_MAX_OUTPUT_CHARS,
|
|
51
|
+
)
|
|
52
|
+
requested_bytes = _positive(args.get("maxBytes"), "maxBytes", byte_ceiling)
|
|
53
|
+
requested_pages = _positive(args.get("maxPages"), "maxPages", page_ceiling)
|
|
54
|
+
requested_output = _positive(args.get("maxOutputChars"), "maxOutputChars", output_ceiling)
|
|
55
|
+
return min(requested_bytes, byte_ceiling), min(requested_pages, page_ceiling), min(requested_output, output_ceiling)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read(args: dict[str, Any]) -> dict[str, Any]:
|
|
59
|
+
"""读一个 HTTP(S) PDF,返回页数、文本与截断标记。"""
|
|
60
|
+
import guard
|
|
61
|
+
import media
|
|
62
|
+
from adapters import AdapterError, _positive_number, _string_map, _url, clip
|
|
63
|
+
|
|
64
|
+
if not available():
|
|
65
|
+
raise _error(
|
|
66
|
+
"DEPENDENCY_MISSING",
|
|
67
|
+
f"pypdf {PYPDF_VERSION} is not installed; run dsh-scrapling setup --feature documents --apply",
|
|
68
|
+
)
|
|
69
|
+
url = _url(args)
|
|
70
|
+
allowed, reason = guard.url_allowed(url)
|
|
71
|
+
if not allowed:
|
|
72
|
+
raise _error("URL_BLOCKED", f"{url}: {reason}")
|
|
73
|
+
max_bytes, max_pages, max_output_chars = _limits(args)
|
|
74
|
+
headers = _string_map(args.get("headers"), "headers")
|
|
75
|
+
cookies = _string_map(args.get("cookies"), "cookies")
|
|
76
|
+
timeout = _positive_number(args.get("timeoutSeconds"), "timeoutSeconds", 120.0)
|
|
77
|
+
impersonate = args.get("impersonate")
|
|
78
|
+
if not isinstance(impersonate, str) or not impersonate:
|
|
79
|
+
impersonate = "chrome"
|
|
80
|
+
|
|
81
|
+
# TemporaryDirectory 包住整个读取过程:头部预检、流式超限、解析失败与加密/扫描
|
|
82
|
+
# 分支都走同一个 finally,不把远端 PDF 留在用户目录或系统临时目录里。
|
|
83
|
+
with tempfile.TemporaryDirectory(prefix="dsh-scrapling-document-") as temporary:
|
|
84
|
+
downloaded = media._download_via_stream(
|
|
85
|
+
url,
|
|
86
|
+
name="document.pdf",
|
|
87
|
+
directory=Path(temporary),
|
|
88
|
+
limit=max_bytes,
|
|
89
|
+
timeout=timeout,
|
|
90
|
+
headers=headers,
|
|
91
|
+
cookies=cookies,
|
|
92
|
+
impersonate=impersonate,
|
|
93
|
+
too_large_code="PDF_TOO_LARGE",
|
|
94
|
+
)
|
|
95
|
+
try:
|
|
96
|
+
from pypdf import PdfReader
|
|
97
|
+
except ImportError as error:
|
|
98
|
+
raise _error("DEPENDENCY_MISSING", f"pypdf {PYPDF_VERSION} is not installed") from error
|
|
99
|
+
try:
|
|
100
|
+
reader = PdfReader(downloaded["path"])
|
|
101
|
+
if reader.is_encrypted:
|
|
102
|
+
raise _error("PDF_ENCRYPTED", "encrypted PDFs are not supported; provide an unencrypted copy")
|
|
103
|
+
page_count = len(reader.pages)
|
|
104
|
+
if page_count > max_pages:
|
|
105
|
+
raise _error(
|
|
106
|
+
"PDF_TOO_LARGE",
|
|
107
|
+
f"PDF has {page_count} pages, over the {max_pages}-page cap",
|
|
108
|
+
)
|
|
109
|
+
texts: list[str] = []
|
|
110
|
+
for index in range(page_count):
|
|
111
|
+
raise_if_cancelled()
|
|
112
|
+
texts.append(reader.pages[index].extract_text() or "")
|
|
113
|
+
if not any(text.strip() for text in texts):
|
|
114
|
+
raise _error("PDF_SCANNED", "PDF has no extractable text; scanned pages need OCR")
|
|
115
|
+
content = "\n\n".join(f"--- Page {index + 1} ---\n{text.strip()}" for index, text in enumerate(texts))
|
|
116
|
+
except AdapterError:
|
|
117
|
+
raise
|
|
118
|
+
except Exception as error:
|
|
119
|
+
raise _error("FETCH_FAILED", f"could not read PDF: {type(error).__name__}: {error}") from error
|
|
120
|
+
content, truncated = clip(content, max_output_chars)
|
|
121
|
+
return {
|
|
122
|
+
"url": url,
|
|
123
|
+
"bytes": downloaded["bytes"],
|
|
124
|
+
"pageCount": page_count,
|
|
125
|
+
"pagesRead": page_count,
|
|
126
|
+
"content": content,
|
|
127
|
+
"truncated": truncated,
|
|
128
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pypdf==7.2.0 --hash=sha256:5edb9b033dd55cecead9303370e6854c1a3b979669bde1c46024cde0228405b1
|
package/py/extraction.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""选择器查询与字段抽取的纯函数。
|
|
2
2
|
|
|
3
3
|
只做 HTML 到 Python 值的转换;不读环境、不发请求、不处理 protocol 帧。
|
|
4
|
-
`adapters.select` 负责参数错误码,`locate`/`links`
|
|
4
|
+
`adapters.select` 负责参数错误码,`locate`/`links` 复用这里的查询与序列化。
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
@@ -464,7 +464,7 @@ def links(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
464
464
|
extractor = LinkExtractor(**options)
|
|
465
465
|
except Exception as error:
|
|
466
466
|
raise ValueError(f"invalid link rule: {error}") from error
|
|
467
|
-
# 上游把注解写成 Response,实际只读 .url 与 .css
|
|
467
|
+
# 上游把注解写成 Response,实际只读 .url 与 .css;传 Selector 实测可用。
|
|
468
468
|
urls = list(extractor.extract(cast(Any, page)))
|
|
469
469
|
truncated = len(urls) > limit
|
|
470
470
|
kept = urls[:limit]
|
package/py/media.py
CHANGED
|
@@ -177,6 +177,7 @@ def _download_via_stream(
|
|
|
177
177
|
headers: dict[str, str] | None,
|
|
178
178
|
cookies: dict[str, str] | None,
|
|
179
179
|
impersonate: str,
|
|
180
|
+
too_large_code: str = "DOWNLOAD_TOO_LARGE",
|
|
180
181
|
) -> dict[str, Any]:
|
|
181
182
|
"""流式下载:逐块落盘并计哈希,内存占用与块同阶,与响应体大小无关。
|
|
182
183
|
|
|
@@ -217,10 +218,10 @@ def _download_via_stream(
|
|
|
217
218
|
if not 200 <= status < 300:
|
|
218
219
|
raise _error("DOWNLOAD_FAILED", f"download answered HTTP {status}")
|
|
219
220
|
declared = _header_value(response.headers, "Content-Length")
|
|
220
|
-
#
|
|
221
|
+
# 头部预检在正文传输之前给出结论;谎报长度的服务端由流式循环里的复核拦下。
|
|
221
222
|
if declared.isdigit() and int(declared) > limit:
|
|
222
223
|
raise _error(
|
|
223
|
-
|
|
224
|
+
too_large_code,
|
|
224
225
|
f"download is {int(declared)} bytes by Content-Length, over the {limit}-byte cap",
|
|
225
226
|
)
|
|
226
227
|
digest = hashlib.sha256()
|
|
@@ -232,7 +233,7 @@ def _download_via_stream(
|
|
|
232
233
|
# 先判后写:写盘再判会让写到磁盘字节超过上限最多一个块(64 KiB)。
|
|
233
234
|
if total + len(chunk) > limit:
|
|
234
235
|
raise _error(
|
|
235
|
-
|
|
236
|
+
too_large_code,
|
|
236
237
|
f"download is over the {limit}-byte cap"
|
|
237
238
|
+ (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
|
|
238
239
|
)
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
# Optional PDF support is pinned separately in documents-requirements.txt.
|
|
1
2
|
annotated-types==0.8.0 --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
|
|
2
3
|
anyio==4.15.1 --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101
|
|
3
4
|
apify_fingerprint_datapoints==0.15.0 --hash=sha256:fc9299b3136880f47b468897cd00ac622ad2c2a93e9cc9f972d10dbf5ed2b3aa
|
|
4
5
|
attrs==26.1.0 --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309
|
|
5
6
|
beautifulsoup4==4.15.0 --hash=sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9
|
|
6
7
|
browserforge==1.2.4 --hash=sha256:fb1c14e62ac09de221dcfc73074200269f697596c642cb200ceaab1127a17542
|
|
7
|
-
certifi==2026.
|
|
8
|
+
certifi==2026.11.20 --hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f
|
|
8
9
|
cffi==2.1.1 --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72
|
|
9
10
|
click==8.5.0 --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360
|
|
10
11
|
cryptography==50.0.2 --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb
|
|
@@ -22,7 +23,7 @@ markdownify==1.2.3 --hash=sha256:a189a0bedfd14009030fde5f85bb6f77c56897cb839b5c2
|
|
|
22
23
|
mcp==2.3.0 --hash=sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377
|
|
23
24
|
mcp-types==2.3.0 --hash=sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d
|
|
24
25
|
msgspec==0.22.0 --hash=sha256:dd9568695911055440d2bb7099ed9098fc181d335daa772d0eb3fe8f31ba4efb
|
|
25
|
-
opentelemetry-api==1.45.
|
|
26
|
+
opentelemetry-api==1.45.2 --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34
|
|
26
27
|
orjson==3.13.0 --hash=sha256:91d933e668ff0ffe164d7c2daec36beba6d1ce7fadb71538fbe142a71f8a1e6e
|
|
27
28
|
patchright==1.64.2 --hash=sha256:c36a071c259f6e99f5b69ec5a2c4993ea3c274b04d324eed914e5937b0d7c218
|
|
28
29
|
playwright==1.64.1 --hash=sha256:59f7b041284ce8d1b72098ae50ca48a2d83692eec25154ab5ba79d4b6b4fe8a9
|
|
@@ -38,7 +39,7 @@ referencing==0.37.0 --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb
|
|
|
38
39
|
rpds-py==2026.9.1 --hash=sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35
|
|
39
40
|
scrapling==0.5.1 --hash=sha256:c9eb0ef22a05e00e19827a179544fea2bc91b663585f637d428453d3b00ceb17
|
|
40
41
|
six==1.17.0 --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274
|
|
41
|
-
soupsieve==
|
|
42
|
+
soupsieve==4.1.3 --hash=sha256:7a390d1a57d1ab7bb228531e9b8a750a5ebf87db774e0ef6faeeac057d22a5bf
|
|
42
43
|
sse-starlette==3.6.0 --hash=sha256:e4dfa4d237d2712cb2b4d4918eda9b457cd6b44bbecdc838af75de836565bafd
|
|
43
44
|
starlette==1.10.0 --hash=sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4
|
|
44
45
|
tld==0.13.2 --hash=sha256:9b8fdbdb880e7ba65b216a4937f2c94c49a7226723783d5838fc958ac76f4e0c
|