@jayyuen66/dsh-scrapling 0.1.2 → 0.1.4
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 +83 -0
- package/README.md +141 -19
- package/README.zh-CN.md +141 -19
- package/THIRD_PARTY_NOTICES.md +20 -2
- package/bin/dsh-scrapling.mjs +13 -0
- package/client.js +11 -3
- package/cordis.patch.yml +1 -1
- package/host.js +40 -36
- package/package.json +26 -9
- package/py/adapters.py +763 -267
- package/py/bridge.py +27 -4
- package/py/crawl.py +640 -90
- package/py/extraction.py +400 -0
- package/py/guard.py +120 -27
- package/py/media.py +474 -0
- package/py/redact.py +118 -0
- package/py/redis_storage.py +129 -0
- package/py/runtime-requirements.txt +49 -0
- package/py/search.py +404 -0
- package/py/session_page.py +240 -0
- package/runtime-manifest.json +16 -0
package/py/adapters.py
CHANGED
|
@@ -19,8 +19,10 @@ css/xpath。浏览器引擎是**一次性 session**:每次调用开进程、
|
|
|
19
19
|
|
|
20
20
|
from __future__ import annotations
|
|
21
21
|
|
|
22
|
+
import codecs
|
|
22
23
|
import concurrent.futures
|
|
23
24
|
import contextlib
|
|
25
|
+
import json
|
|
24
26
|
import queue
|
|
25
27
|
import re
|
|
26
28
|
import sys
|
|
@@ -28,10 +30,13 @@ import threading
|
|
|
28
30
|
import uuid
|
|
29
31
|
from datetime import datetime, timezone
|
|
30
32
|
from pathlib import Path
|
|
31
|
-
from typing import Any, Callable
|
|
32
|
-
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
33
|
+
from typing import Any, Callable, NamedTuple
|
|
33
34
|
|
|
35
|
+
import extraction
|
|
34
36
|
import guard
|
|
37
|
+
import media
|
|
38
|
+
import search
|
|
39
|
+
from redact import redact_url_secrets
|
|
35
40
|
|
|
36
41
|
# Scrapling 缺失时不要让整个 sidecar 起不来:桥接层会把它报成能力缺失,
|
|
37
42
|
# 而不是让 Host 侧只看到一个「进程崩了」。
|
|
@@ -51,7 +56,7 @@ DEFAULT_MAX_CONTENT_CHARS = 200_000
|
|
|
51
56
|
# 量级,而这份摘要是给模型看的 —— 两个预算都由本包定,不由上游存了多少决定。
|
|
52
57
|
DEFAULT_NETWORK_ENTRIES = 50
|
|
53
58
|
DEFAULT_NETWORK_BODY_CHARS = 20_000
|
|
54
|
-
EXTRACTION_TYPES = ("markdown", "html", "text")
|
|
59
|
+
EXTRACTION_TYPES = ("markdown", "html", "text", "json")
|
|
55
60
|
# adaptive 指纹库的文件名。**相对路径**:bridge 由宿主以部署侧的 dataDir 为工作目录拉起
|
|
56
61
|
# (见 host.ts 的 sidecar env),相对路径正好把库落进 dataDir —— Scrapling 自己的默认值
|
|
57
62
|
# 是包目录内的绝对路径,那在只读的 site-packages 里写不了,也不是用户该找的地方。
|
|
@@ -61,9 +66,10 @@ ADAPTIVE_STORAGE_FILE = "elements_storage.db"
|
|
|
61
66
|
class AdapterError(RuntimeError):
|
|
62
67
|
"""带机器可读错误码的抓取失败。"""
|
|
63
68
|
|
|
64
|
-
def __init__(self, code: str, message: str) -> None:
|
|
69
|
+
def __init__(self, code: str, message: str, *, details: dict[str, Any] | None = None) -> None:
|
|
65
70
|
super().__init__(message)
|
|
66
71
|
self.code = code
|
|
72
|
+
self.details = details or {}
|
|
67
73
|
|
|
68
74
|
|
|
69
75
|
def _require(engine: object) -> None:
|
|
@@ -85,6 +91,20 @@ def _positive_int(value: Any, field: str, default: int) -> int:
|
|
|
85
91
|
return value
|
|
86
92
|
|
|
87
93
|
|
|
94
|
+
def _bounded_int(value: Any, field: str, default: int, maximum: int) -> int:
|
|
95
|
+
"""取一个 ``1..maximum`` 的整数。
|
|
96
|
+
|
|
97
|
+
上限不是本包随口定的:上游把浏览器会话的这两个键写成 ``RetriesCount = Annotated[int,
|
|
98
|
+
Meta(ge=1, le=10)]`` 与 ``PagesCount = Annotated[int, Meta(ge=1, le=50)]``,越界值不在
|
|
99
|
+
Scrapling 里被拒,而是在它的 msgspec 校验层炸成 ``TypeError``,再由本包归成一次抓取失败。
|
|
100
|
+
这里先判,是为了把「旋钮拧过了」说成一句参数错误。
|
|
101
|
+
"""
|
|
102
|
+
number = _positive_int(value, field, default)
|
|
103
|
+
if number > maximum:
|
|
104
|
+
raise AdapterError("BAD_ARGS", f"{field} must be between 1 and {maximum}")
|
|
105
|
+
return number
|
|
106
|
+
|
|
107
|
+
|
|
88
108
|
def _positive_number(value: Any, field: str, default: float) -> float:
|
|
89
109
|
"""取一个正数。"""
|
|
90
110
|
if value is None:
|
|
@@ -128,110 +148,22 @@ def _jsonable(value: Any) -> Any:
|
|
|
128
148
|
return str(value)
|
|
129
149
|
|
|
130
150
|
|
|
131
|
-
#
|
|
132
|
-
# 上下文、进日志、进第三方 provider——而真实站点把 access token、会话 id、签名都放在
|
|
133
|
-
# 查询串里。抓到一条就等于把凭据抄进上下文,而模型既用不上它、也拦不住它被复述出来。
|
|
134
|
-
# 值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是那个 token。
|
|
135
|
-
_SECRET_QUERY_KEYS = frozenset(
|
|
136
|
-
{
|
|
137
|
-
"access_token",
|
|
138
|
-
"api_key",
|
|
139
|
-
"apikey",
|
|
140
|
-
"auth",
|
|
141
|
-
"auth_token",
|
|
142
|
-
"authorization",
|
|
143
|
-
"code",
|
|
144
|
-
"credential",
|
|
145
|
-
"id_token",
|
|
146
|
-
"key",
|
|
147
|
-
"password",
|
|
148
|
-
"pwd",
|
|
149
|
-
"refresh_token",
|
|
150
|
-
"secret",
|
|
151
|
-
"session",
|
|
152
|
-
"sessionid",
|
|
153
|
-
"session_id",
|
|
154
|
-
"sig",
|
|
155
|
-
"signature",
|
|
156
|
-
"sign",
|
|
157
|
-
"token",
|
|
158
|
-
}
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
def _redacted_query(text: str) -> str:
|
|
163
|
-
"""把一段查询串里像凭据的参数值换成占位符;没有命中时原样返回。
|
|
164
|
-
|
|
165
|
-
与 :func:`redact_url_secrets` 同一套参数名判据,片段也复用它 —— OAuth2 隐式流程把
|
|
166
|
-
令牌放在 ``#access_token=`` 里,那同样是「给模型看就等于抄进上下文」的凭据。
|
|
167
|
-
|
|
168
|
-
:param text: 查询串(或片段的查询部分)
|
|
169
|
-
:returns: 脱敏后的文本
|
|
170
|
-
"""
|
|
171
|
-
if not text:
|
|
172
|
-
return text
|
|
173
|
-
pairs: list[tuple[str, str]] = []
|
|
174
|
-
changed = False
|
|
175
|
-
for name, value in parse_qsl(text, keep_blank_values=True):
|
|
176
|
-
if name.strip().lower() in _SECRET_QUERY_KEYS:
|
|
177
|
-
pairs.append((name, "<redacted>"))
|
|
178
|
-
changed = True
|
|
179
|
-
else:
|
|
180
|
-
pairs.append((name, value))
|
|
181
|
-
if not changed:
|
|
182
|
-
return text
|
|
183
|
-
return urlencode(pairs)
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
def _redacted_fragment(fragment: str) -> str:
|
|
187
|
-
"""把片段里像查询串的那一段脱敏;没有命中时原样返回。
|
|
151
|
+
# 查询串与 authority 的凭据脱敏在 py/redact.py:guard 的日志与网络摘要共用同一份。
|
|
188
152
|
|
|
189
|
-
|
|
190
|
-
单页应用的路由则是先路径后查询(``#!/list?token=…``)。两种都要覆盖。
|
|
153
|
+
_SENSITIVE_HEADERS = frozenset({"set-cookie", "cookie", "authorization", "proxy-authorization"})
|
|
191
154
|
|
|
192
|
-
:param fragment: URL 的 fragment 段
|
|
193
|
-
:returns: 脱敏后的 fragment
|
|
194
|
-
"""
|
|
195
|
-
head, separator, query = fragment.partition("?")
|
|
196
|
-
if separator:
|
|
197
|
-
return f"{head}?{_redacted_query(query)}"
|
|
198
|
-
return _redacted_query(fragment)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
def redact_url_secrets(raw: str) -> str:
|
|
202
|
-
"""把 URL 里像凭据的部分替换成占位符。
|
|
203
|
-
|
|
204
|
-
三处各藏一类凭据:查询串与片段的查询部分按**参数名**判(真实站点把 access token、
|
|
205
|
-
会话 id、签名放在那里),authority 里的 ``user:pass@`` 整段丢掉(代理与 Basic 认证
|
|
206
|
-
的接口都爱这么写)。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是
|
|
207
|
-
那个 token。
|
|
208
155
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
:
|
|
214
|
-
"""
|
|
215
|
-
try:
|
|
216
|
-
parsed = urlsplit(raw)
|
|
217
|
-
except ValueError:
|
|
218
|
-
return raw
|
|
219
|
-
# rpartition 取最后一段:IPv6 字面量与端口都留在主机那一侧,只把用户信息摘掉。
|
|
220
|
-
netloc = parsed.netloc.rpartition("@")[2]
|
|
221
|
-
query = _redacted_query(parsed.query)
|
|
222
|
-
fragment = _redacted_fragment(parsed.fragment)
|
|
223
|
-
if netloc == parsed.netloc and query == parsed.query and fragment == parsed.fragment:
|
|
224
|
-
return raw
|
|
225
|
-
return urlunsplit((parsed.scheme, netloc, parsed.path, query, fragment))
|
|
156
|
+
def _safe_headers(headers: Any) -> dict[str, str]:
|
|
157
|
+
"""只回非凭据响应头;cookie 与鉴权头一律不出口。"""
|
|
158
|
+
if not isinstance(headers, dict):
|
|
159
|
+
return {}
|
|
160
|
+
return {str(key): str(value) for key, value in headers.items() if str(key).lower() not in _SENSITIVE_HEADERS}
|
|
226
161
|
|
|
227
162
|
|
|
228
163
|
def _network_summary(
|
|
229
164
|
network: Any, # 上游的 NetworkRecorder
|
|
230
165
|
*,
|
|
231
|
-
|
|
232
|
-
limit: int,
|
|
233
|
-
include_body: bool,
|
|
234
|
-
max_body_chars: int,
|
|
166
|
+
query: _NetworkQuery,
|
|
235
167
|
) -> list[dict[str, Any]]:
|
|
236
168
|
"""把会话网络历史压成给模型看的条目。
|
|
237
169
|
|
|
@@ -248,7 +180,19 @@ def _network_summary(
|
|
|
248
180
|
"""
|
|
249
181
|
summary: list[dict[str, Any]] = []
|
|
250
182
|
try:
|
|
251
|
-
|
|
183
|
+
if query.request_id is not None:
|
|
184
|
+
record = network.get(query.request_id)
|
|
185
|
+
records = [] if record is None else [record]
|
|
186
|
+
else:
|
|
187
|
+
records = network.search(
|
|
188
|
+
url_pattern=query.pattern,
|
|
189
|
+
method=query.method,
|
|
190
|
+
resource_type=query.resource_type,
|
|
191
|
+
status=query.status,
|
|
192
|
+
after_id=query.after_id,
|
|
193
|
+
limit=query.limit,
|
|
194
|
+
include_static=query.include_static,
|
|
195
|
+
)
|
|
252
196
|
except Exception: # noqa: BLE001 —— 记录器未启用或上游改了口径:当成「没有历史」
|
|
253
197
|
return summary
|
|
254
198
|
for item in records:
|
|
@@ -256,24 +200,30 @@ def _network_summary(
|
|
|
256
200
|
meta = item.meta if isinstance(item.meta, dict) else {}
|
|
257
201
|
body = item.body
|
|
258
202
|
entry: dict[str, Any] = {
|
|
203
|
+
"id": int(meta.get("network_id") or 0),
|
|
259
204
|
"url": redact_url_secrets(str(item.url)),
|
|
260
205
|
"status": item.status,
|
|
261
206
|
"bytes": len(body),
|
|
262
|
-
|
|
207
|
+
# 上游把方法记在 Response.method 上;从 meta / request_headers 读会退化成 GET,
|
|
208
|
+
# POST 的 XHR 在摘要里一律显示成 GET(V5 已复现)。
|
|
209
|
+
"method": str(getattr(item, "method", "GET")),
|
|
263
210
|
"resourceType": str(meta.get("resource_type") or ""),
|
|
264
211
|
}
|
|
212
|
+
if query.include_headers:
|
|
213
|
+
entry["headers"] = _safe_headers(getattr(item, "headers", {}))
|
|
265
214
|
if not body:
|
|
266
215
|
note = meta.get("body_note")
|
|
267
216
|
if isinstance(note, str) and note:
|
|
268
217
|
entry["bodyNote"] = note
|
|
269
|
-
elif include_body:
|
|
218
|
+
elif query.include_body:
|
|
270
219
|
text = body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body)
|
|
271
|
-
clipped, truncated = clip(text,
|
|
220
|
+
clipped, truncated = clip(text, query.body_chars)
|
|
272
221
|
entry["body"] = clipped
|
|
273
222
|
if truncated:
|
|
274
223
|
entry["bodyTruncated"] = True
|
|
275
224
|
summary.append(entry)
|
|
276
|
-
|
|
225
|
+
# 单条摘要失败不该拖垮整次读取;继续处理下一条。
|
|
226
|
+
except Exception: # noqa: BLE001, S112 # nosec B112
|
|
277
227
|
continue
|
|
278
228
|
return summary
|
|
279
229
|
|
|
@@ -411,6 +361,30 @@ def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # 同上
|
|
|
411
361
|
return list(page.css(css_selector))
|
|
412
362
|
|
|
413
363
|
|
|
364
|
+
def _header_value(headers: Any, name: str) -> str:
|
|
365
|
+
"""按大小写不敏感读一个响应头;缺失给空串。"""
|
|
366
|
+
if not isinstance(headers, dict):
|
|
367
|
+
return ""
|
|
368
|
+
wanted = name.lower()
|
|
369
|
+
for key, value in headers.items():
|
|
370
|
+
if str(key).lower() == wanted:
|
|
371
|
+
return str(value)
|
|
372
|
+
return ""
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _response_metadata(response: Any, redirects: int) -> dict[str, Any]:
|
|
376
|
+
"""只收安全子集:不返回 cookie、set-cookie 或任何鉴权头。"""
|
|
377
|
+
headers = getattr(response, "headers", {}) or {}
|
|
378
|
+
request = getattr(response, "request", None)
|
|
379
|
+
return {
|
|
380
|
+
"contentType": _header_value(headers, "content-type"),
|
|
381
|
+
"encoding": str(getattr(response, "encoding", "") or ""),
|
|
382
|
+
"reason": str(getattr(response, "reason", "") or ""),
|
|
383
|
+
"redirects": redirects,
|
|
384
|
+
"method": str(getattr(request, "method", "GET")),
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
|
|
414
388
|
def to_payload(
|
|
415
389
|
response: Any,
|
|
416
390
|
*,
|
|
@@ -419,43 +393,64 @@ def to_payload(
|
|
|
419
393
|
main_content_only: bool,
|
|
420
394
|
max_content_chars: int,
|
|
421
395
|
strip_inline_images: bool = True,
|
|
396
|
+
include_metadata: bool = False,
|
|
422
397
|
) -> dict[str, Any]:
|
|
423
398
|
"""把 Scrapling 的 ``Response`` 归一成协议载荷。
|
|
424
399
|
|
|
425
400
|
反注入清洗对三条提取路径都无条件发生(``Convertor._strip_noise_tags`` +
|
|
426
401
|
``_sanitize_for_ai``)—— 这里**不提供关闭它的开关**。官方 MCP server 在
|
|
427
402
|
``main_content_only=False`` 时会绕过清洗,本插件不重复这个错。
|
|
403
|
+
|
|
404
|
+
``json`` 是数据而不是正文:直接解析并序列化,不过 markdown 反注入清洗;但序列化后的
|
|
405
|
+
文本照旧剥 data URI(内联图片对模型不可读,还会白吃 ``maxContentChars`` 的额度)并受
|
|
406
|
+
同一个 ``maxContentChars`` 封顶——与 html/text/markdown 三条路径同一套收口(spec:363)。
|
|
428
407
|
"""
|
|
429
|
-
if extraction_type == "
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
)
|
|
440
|
-
|
|
441
|
-
)
|
|
408
|
+
if extraction_type == "json":
|
|
409
|
+
try:
|
|
410
|
+
parsed = response.json()
|
|
411
|
+
except Exception as error:
|
|
412
|
+
raw = getattr(response, "html_content", "") or getattr(response, "text", "")
|
|
413
|
+
raise AdapterError("NOT_JSON", f"response is not JSON: {str(raw)[:200]}") from error
|
|
414
|
+
text = json.dumps(parsed, ensure_ascii=False)
|
|
415
|
+
# spec:363 —— JSON 文本与正文走同一条剥图/清洗再封顶的路径:序列化之后的 data URI
|
|
416
|
+
# 同样会白吃 maxContentChars 的额度,而且内联图片是模型读不懂的字节。
|
|
417
|
+
if strip_inline_images:
|
|
418
|
+
text = drop_data_uris(text)
|
|
419
|
+
clipped, truncated = clip(text, max_content_chars)
|
|
442
420
|
else:
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
421
|
+
if extraction_type == "html":
|
|
422
|
+
page = _sanitized_page(response, main_content_only=main_content_only)
|
|
423
|
+
_strip_active_content(page)
|
|
424
|
+
content = "\n".join(element.html_content for element in _scoped_pages(page, css_selector))
|
|
425
|
+
elif extraction_type == "text":
|
|
426
|
+
page = _sanitized_page(response, main_content_only=main_content_only)
|
|
427
|
+
content = "\n".join(
|
|
428
|
+
element.get_all_text(
|
|
429
|
+
strip=True,
|
|
430
|
+
ignore_tags=("script", "style", "noscript", "svg", "iframe"),
|
|
431
|
+
)
|
|
432
|
+
for element in _scoped_pages(page, css_selector)
|
|
433
|
+
)
|
|
434
|
+
else:
|
|
435
|
+
content = response.markdown(css_selector=css_selector, main_content_only=main_content_only)
|
|
436
|
+
text = str(content)
|
|
437
|
+
# 先剥再封顶:被剥掉的那几十 KB 不该占 max_content_chars 的额度,否则一页内联图就能把
|
|
438
|
+
# 真正文挤出预算 —— 顺序反了等于白剥。
|
|
439
|
+
if strip_inline_images:
|
|
440
|
+
text = drop_data_uris(text, html=extraction_type == "html")
|
|
441
|
+
clipped, truncated = clip(text, max_content_chars)
|
|
442
|
+
|
|
443
|
+
redirects = len(getattr(response, "history", ()) or ())
|
|
451
444
|
payload: dict[str, Any] = {
|
|
452
445
|
"url": response.url,
|
|
453
446
|
"status": response.status,
|
|
454
447
|
"extractionType": extraction_type,
|
|
455
448
|
"content": clipped,
|
|
456
449
|
"truncated": truncated,
|
|
457
|
-
"redirects":
|
|
450
|
+
"redirects": redirects,
|
|
458
451
|
}
|
|
452
|
+
if include_metadata:
|
|
453
|
+
payload["metadata"] = _response_metadata(response, redirects)
|
|
459
454
|
return payload
|
|
460
455
|
|
|
461
456
|
|
|
@@ -500,6 +495,42 @@ def _static_params(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
|
500
495
|
return params
|
|
501
496
|
|
|
502
497
|
|
|
498
|
+
def _object_param(value: Any, field: str) -> dict[str, Any] | None:
|
|
499
|
+
"""取一个可选的对象参数;类型不对就报错。"""
|
|
500
|
+
if value is None:
|
|
501
|
+
return None
|
|
502
|
+
if not isinstance(value, dict):
|
|
503
|
+
raise AdapterError("BAD_ARGS", f"{field} must be an object or null")
|
|
504
|
+
return value
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _string_set(value: Any, field: str) -> set[str] | None:
|
|
508
|
+
"""取一个可选的字符串数组并转成集合。"""
|
|
509
|
+
if value is None:
|
|
510
|
+
return None
|
|
511
|
+
if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value):
|
|
512
|
+
raise AdapterError("BAD_ARGS", f"{field} must be an array of non-empty strings or null")
|
|
513
|
+
return set(value)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _cookie_list(value: Any) -> list[dict[str, Any]] | None:
|
|
517
|
+
"""校验 Playwright 兼容的 cookie 列表;只要求 name/value 是字符串。"""
|
|
518
|
+
if value is None:
|
|
519
|
+
return None
|
|
520
|
+
if not isinstance(value, list):
|
|
521
|
+
raise AdapterError("BAD_ARGS", "cookies must be an array or null")
|
|
522
|
+
cookies: list[dict[str, Any]] = []
|
|
523
|
+
for item in value:
|
|
524
|
+
if not isinstance(item, dict):
|
|
525
|
+
raise AdapterError("BAD_ARGS", "cookies must contain objects")
|
|
526
|
+
name = item.get("name")
|
|
527
|
+
cookie_value = item.get("value")
|
|
528
|
+
if not isinstance(name, str) or not name or not isinstance(cookie_value, str):
|
|
529
|
+
raise AdapterError("BAD_ARGS", "each cookie needs string name and value fields")
|
|
530
|
+
cookies.append(dict(item))
|
|
531
|
+
return cookies
|
|
532
|
+
|
|
533
|
+
|
|
503
534
|
def _url(args: dict[str, Any]) -> str:
|
|
504
535
|
"""取必填的 url 参数。"""
|
|
505
536
|
url = args.get("url")
|
|
@@ -508,6 +539,93 @@ def _url(args: dict[str, Any]) -> str:
|
|
|
508
539
|
return url
|
|
509
540
|
|
|
510
541
|
|
|
542
|
+
def _static_request_payload(args: dict[str, Any], method: str) -> dict[str, Any]:
|
|
543
|
+
"""静态请求的查询串、请求体、编码与重试细节。
|
|
544
|
+
|
|
545
|
+
先校验再交给写方法门禁:``form`` 与 ``json`` 同时给出是参数错误(``BAD_ARGS``),
|
|
546
|
+
不该被写方法那条部署表态盖掉。
|
|
547
|
+
"""
|
|
548
|
+
query = _object_param(args.get("params"), "params")
|
|
549
|
+
form = _object_param(args.get("form"), "form")
|
|
550
|
+
json_body = args.get("json")
|
|
551
|
+
if form is not None and json_body is not None:
|
|
552
|
+
raise AdapterError("BAD_ARGS", "form and json are mutually exclusive")
|
|
553
|
+
if args.get("body") is not None and (form is not None or json_body is not None):
|
|
554
|
+
raise AdapterError("BAD_ARGS", "body cannot be combined with form or json")
|
|
555
|
+
default_encoding = args.get("defaultEncoding")
|
|
556
|
+
if default_encoding is not None and not isinstance(default_encoding, str):
|
|
557
|
+
raise AdapterError("BAD_ARGS", "defaultEncoding must be a string or null")
|
|
558
|
+
retry_delay = _positive_int(args.get("retryDelay"), "retryDelay", 1) if args.get("retryDelay") is not None else None
|
|
559
|
+
stealthy_headers = args.get("stealthyHeaders", True)
|
|
560
|
+
if not isinstance(stealthy_headers, bool):
|
|
561
|
+
raise AdapterError("BAD_ARGS", "stealthyHeaders must be a boolean")
|
|
562
|
+
|
|
563
|
+
payload: dict[str, Any] = {}
|
|
564
|
+
if query is not None:
|
|
565
|
+
payload["params"] = query
|
|
566
|
+
cookies = _string_map(args.get("cookies"), "cookies")
|
|
567
|
+
if cookies is not None:
|
|
568
|
+
payload["cookies"] = cookies
|
|
569
|
+
if isinstance(default_encoding, str) and default_encoding:
|
|
570
|
+
# default_encoding 不在 Scrapling 声明的 GET/POST 参数面里,它是 _merge_request_args
|
|
571
|
+
# 原样透传给 curl_cffi 的 Session.request 的那一位;编码名先经 codecs 归一,
|
|
572
|
+
# 但 curl_cffi 若改名,这一位会由它自己报错而不是在这里被拦住。
|
|
573
|
+
try:
|
|
574
|
+
payload["default_encoding"] = codecs.lookup(default_encoding).name
|
|
575
|
+
except LookupError as error:
|
|
576
|
+
raise AdapterError("BAD_ARGS", f"defaultEncoding is not a known encoding: {default_encoding}") from error
|
|
577
|
+
if retry_delay is not None:
|
|
578
|
+
payload["retry_delay"] = retry_delay
|
|
579
|
+
if stealthy_headers is False:
|
|
580
|
+
payload["stealthy_headers"] = False
|
|
581
|
+
|
|
582
|
+
if method != "GET":
|
|
583
|
+
if form is not None:
|
|
584
|
+
payload["data"] = form
|
|
585
|
+
elif json_body is not None:
|
|
586
|
+
payload["json"] = _jsonable(json_body)
|
|
587
|
+
else:
|
|
588
|
+
body = args.get("body")
|
|
589
|
+
if isinstance(body, str):
|
|
590
|
+
payload["data"] = body
|
|
591
|
+
elif body is not None:
|
|
592
|
+
# 数组、数字、布尔也是合法的 JSON 请求体(curl_cffi 的 ``json=`` 照收)。此前只有
|
|
593
|
+
# dict 走 json、str 走 data,其余**静默丢弃** —— 模型发一个 `body: [1, 2]`,请求照
|
|
594
|
+
# 发、对端收到空体,而回包上没有一行能看出这件事。
|
|
595
|
+
payload["json"] = _jsonable(body)
|
|
596
|
+
return payload
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
# 请求体本身就是写意图:给了这些键却把方法留空时按 POST 发,而不是把它们丢进一次
|
|
600
|
+
# GET(那会「发出去但语义错了」,而回包上没有任何一行能看出这件事)。
|
|
601
|
+
_WRITE_BODY_KEYS = ("form", "json", "body")
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _static_method(args: dict[str, Any]) -> str:
|
|
605
|
+
"""定静态抓取的方法:显式 ``method`` 优先,没给时由请求体推。
|
|
606
|
+
|
|
607
|
+
缺省一律 GET 的写法会让 ``form`` / ``json`` / ``body`` **静默落地**:请求照发、
|
|
608
|
+
对端收到空体。所以这三个键在场时默认按 POST 发;而显式 GET 配它们是无解的组
|
|
609
|
+
合 —— 那是参数错误,不是可以静默降级的默认值。
|
|
610
|
+
|
|
611
|
+
:param args: 协议参数
|
|
612
|
+
:returns: ``GET`` / ``POST`` / ``PUT`` / ``DELETE``
|
|
613
|
+
:raises AdapterError: 方法不支持,或显式 GET 带了请求体
|
|
614
|
+
"""
|
|
615
|
+
raw = args.get("method")
|
|
616
|
+
method = str(raw).upper() if raw is not None and raw != "" else ""
|
|
617
|
+
if not method:
|
|
618
|
+
return "POST" if any(args.get(key) is not None for key in _WRITE_BODY_KEYS) else "GET"
|
|
619
|
+
if method not in ("GET", "POST", "PUT", "DELETE"):
|
|
620
|
+
raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
|
|
621
|
+
if method == "GET" and any(args.get(key) is not None for key in _WRITE_BODY_KEYS):
|
|
622
|
+
raise AdapterError(
|
|
623
|
+
"BAD_ARGS",
|
|
624
|
+
"GET cannot carry a request body; drop body/form/json or use a write method such as POST",
|
|
625
|
+
)
|
|
626
|
+
return method
|
|
627
|
+
|
|
628
|
+
|
|
511
629
|
def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
512
630
|
"""静态抓取(curl_cffi)。不需要浏览器。
|
|
513
631
|
|
|
@@ -518,18 +636,8 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
518
636
|
_require(Fetcher)
|
|
519
637
|
url = _url(args)
|
|
520
638
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
cookies = _string_map(args.get("cookies"), "cookies")
|
|
524
|
-
if cookies is not None:
|
|
525
|
-
params["cookies"] = cookies
|
|
526
|
-
impersonate = args.get("impersonate")
|
|
527
|
-
if isinstance(impersonate, str) and impersonate:
|
|
528
|
-
params["impersonate"] = impersonate
|
|
529
|
-
|
|
530
|
-
method = str(args.get("method", "GET")).upper()
|
|
531
|
-
if method not in ("GET", "POST", "PUT", "DELETE"):
|
|
532
|
-
raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
|
|
639
|
+
method = _static_method(args)
|
|
640
|
+
request_payload = _static_request_payload(args, method)
|
|
533
641
|
if method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
534
642
|
# 这一侧是硬拒,不依赖 Host 有没有把入参摆出来:手搓一帧 stdin 也写不出去。
|
|
535
643
|
raise AdapterError(
|
|
@@ -537,15 +645,11 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
537
645
|
f"{method} changes state on the remote side; the deployment must set "
|
|
538
646
|
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
539
647
|
)
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
# 数组、数字、布尔也是合法的 JSON 请求体(curl_cffi 的 ``json=`` 照收)。此前只有
|
|
546
|
-
# dict 走 json、str 走 data,其余**静默丢弃** —— 模型发一个 `body: [1, 2]`,请求照
|
|
547
|
-
# 发、对端收到空体,而回包上没有一行能看出这件事。
|
|
548
|
-
params["json"] = _jsonable(body)
|
|
648
|
+
params = _static_params(args, url)
|
|
649
|
+
params.update(request_payload)
|
|
650
|
+
impersonate = args.get("impersonate")
|
|
651
|
+
if isinstance(impersonate, str) and impersonate:
|
|
652
|
+
params["impersonate"] = impersonate
|
|
549
653
|
|
|
550
654
|
# Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
|
|
551
655
|
# 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
|
|
@@ -554,7 +658,18 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
554
658
|
allowed, reason = guard.url_allowed(url)
|
|
555
659
|
if not allowed:
|
|
556
660
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
557
|
-
|
|
661
|
+
try:
|
|
662
|
+
response = getattr(Fetcher, method.lower())(url, **params)
|
|
663
|
+
except Exception as error:
|
|
664
|
+
# 非法的 impersonate 不是「抓取失败」而是参数错误:curl_cffi 在**请求时**才
|
|
665
|
+
# 校验它,抛的是 ``ImpersonateError``(构造 Session 那一层不校验,所以只能在
|
|
666
|
+
# 这里接)。原文与堆栈对模型没有信息量,换成一句能自己纠正的 BAD_ARGS。
|
|
667
|
+
if type(error).__name__ == "ImpersonateError":
|
|
668
|
+
raise AdapterError(
|
|
669
|
+
"BAD_ARGS",
|
|
670
|
+
f"impersonate {impersonate!r} is not supported by curl_cffi; use one of its supported browser presets",
|
|
671
|
+
) from error
|
|
672
|
+
raise
|
|
558
673
|
return to_payload(
|
|
559
674
|
response,
|
|
560
675
|
extraction_type=extraction_type,
|
|
@@ -562,6 +677,7 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
562
677
|
main_content_only=main_content_only,
|
|
563
678
|
max_content_chars=limit,
|
|
564
679
|
strip_inline_images=_strip_inline_images(args),
|
|
680
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
565
681
|
)
|
|
566
682
|
|
|
567
683
|
|
|
@@ -629,12 +745,17 @@ SESSION_ONLY_KEYS = frozenset(
|
|
|
629
745
|
"allow_webgl",
|
|
630
746
|
"block_ads",
|
|
631
747
|
"block_webrtc",
|
|
748
|
+
"blocked_domains",
|
|
632
749
|
"cdp_url",
|
|
750
|
+
"cookies",
|
|
751
|
+
"disable_resources",
|
|
633
752
|
"dns_over_https",
|
|
634
753
|
"executable_path",
|
|
754
|
+
"google_search",
|
|
635
755
|
"headless",
|
|
636
756
|
"hide_canvas",
|
|
637
757
|
"init_script",
|
|
758
|
+
"load_dom",
|
|
638
759
|
"locale",
|
|
639
760
|
"max_pages",
|
|
640
761
|
"max_recorded_requests",
|
|
@@ -645,6 +766,7 @@ SESSION_ONLY_KEYS = frozenset(
|
|
|
645
766
|
"timezone_id",
|
|
646
767
|
"useragent",
|
|
647
768
|
"user_data_dir",
|
|
769
|
+
"wait_selector_state",
|
|
648
770
|
}
|
|
649
771
|
)
|
|
650
772
|
|
|
@@ -717,12 +839,30 @@ def _browser_params(args: dict[str, Any], url: str, *, level: str = "session") -
|
|
|
717
839
|
"headless": bool(args.get("headless", True)),
|
|
718
840
|
"timeout": _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS),
|
|
719
841
|
"block_ads": bool(args.get("blockAds", False)),
|
|
720
|
-
|
|
721
|
-
|
|
842
|
+
# 这里刻意**不**预置 blocked_domains / disable_resources:见上方 docstring。模型
|
|
843
|
+
# 显式给了才在下面按条件覆盖;没给就交给上游沿用会话配置。
|
|
722
844
|
}
|
|
723
845
|
proxy = guard.browser_proxy(url)
|
|
724
846
|
if proxy is not None:
|
|
725
847
|
params["proxy"] = proxy
|
|
848
|
+
cookies = _cookie_list(args.get("cookies"))
|
|
849
|
+
if cookies is not None:
|
|
850
|
+
params["cookies"] = cookies
|
|
851
|
+
blocked_domains = _string_set(args.get("blockedDomains"), "blockedDomains")
|
|
852
|
+
if blocked_domains is not None:
|
|
853
|
+
params["blocked_domains"] = blocked_domains
|
|
854
|
+
if isinstance(args.get("disableResources"), bool):
|
|
855
|
+
params["disable_resources"] = args["disableResources"]
|
|
856
|
+
if isinstance(args.get("loadDom"), bool):
|
|
857
|
+
params["load_dom"] = args["loadDom"]
|
|
858
|
+
if isinstance(args.get("googleSearch"), bool):
|
|
859
|
+
params["google_search"] = args["googleSearch"]
|
|
860
|
+
if args.get("retries") is not None:
|
|
861
|
+
params["retries"] = _bounded_int(args.get("retries"), "retries", 3, 10)
|
|
862
|
+
if args.get("retryDelay") is not None:
|
|
863
|
+
params["retry_delay"] = _positive_int(args.get("retryDelay"), "retryDelay", 1)
|
|
864
|
+
if args.get("maxPages") is not None:
|
|
865
|
+
params["max_pages"] = _bounded_int(args.get("maxPages"), "maxPages", 1, 50)
|
|
726
866
|
if args.get("networkIdle"):
|
|
727
867
|
params["network_idle"] = True
|
|
728
868
|
for key, name in (
|
|
@@ -805,20 +945,59 @@ def render(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
805
945
|
main_content_only=main_content_only,
|
|
806
946
|
max_content_chars=limit,
|
|
807
947
|
strip_inline_images=_strip_inline_images(args),
|
|
948
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
808
949
|
)
|
|
809
950
|
|
|
810
951
|
|
|
811
|
-
|
|
812
|
-
"""
|
|
952
|
+
class _NetworkQuery(NamedTuple):
|
|
953
|
+
"""一次网络历史读取的全部过滤与投影参数。"""
|
|
954
|
+
|
|
955
|
+
pattern: str | None
|
|
956
|
+
limit: int
|
|
957
|
+
include_body: bool
|
|
958
|
+
body_chars: int
|
|
959
|
+
method: str | None
|
|
960
|
+
status: int | None
|
|
961
|
+
resource_type: str | None
|
|
962
|
+
include_static: bool
|
|
963
|
+
after_id: int
|
|
964
|
+
include_headers: bool
|
|
965
|
+
request_id: int | None
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
def _network_read(args: dict[str, Any]) -> _NetworkQuery:
|
|
969
|
+
"""抽出「读网络历史」的过滤与投影参数并校验。
|
|
813
970
|
|
|
814
971
|
:param args: 协议参数
|
|
815
|
-
:returns:
|
|
972
|
+
:returns: 归一后的查询参数
|
|
816
973
|
"""
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
974
|
+
method = args.get("method")
|
|
975
|
+
if method is not None and (not isinstance(method, str) or not method):
|
|
976
|
+
raise AdapterError("BAD_ARGS", "method must be a non-empty string or null")
|
|
977
|
+
status = args.get("status")
|
|
978
|
+
if status is not None and (not isinstance(status, int) or isinstance(status, bool) or not 100 <= status <= 599):
|
|
979
|
+
raise AdapterError("BAD_ARGS", "status must be an integer between 100 and 599")
|
|
980
|
+
resource_type = args.get("resourceType")
|
|
981
|
+
if resource_type is not None and (not isinstance(resource_type, str) or not resource_type):
|
|
982
|
+
raise AdapterError("BAD_ARGS", "resourceType must be a non-empty string or null")
|
|
983
|
+
after_id = args.get("afterId", 0)
|
|
984
|
+
if not isinstance(after_id, int) or isinstance(after_id, bool) or after_id < 0:
|
|
985
|
+
raise AdapterError("BAD_ARGS", "afterId must be a non-negative integer")
|
|
986
|
+
request_id = args.get("requestId")
|
|
987
|
+
if request_id is not None and (not isinstance(request_id, int) or isinstance(request_id, bool) or request_id <= 0):
|
|
988
|
+
raise AdapterError("BAD_ARGS", "requestId must be a positive integer or null")
|
|
989
|
+
return _NetworkQuery(
|
|
990
|
+
pattern=_url_pattern(args),
|
|
991
|
+
limit=_positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
|
|
992
|
+
include_body=bool(args.get("includeBody", False)),
|
|
993
|
+
body_chars=_positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
|
|
994
|
+
method=method.upper() if isinstance(method, str) else None,
|
|
995
|
+
status=status,
|
|
996
|
+
resource_type=resource_type,
|
|
997
|
+
include_static=bool(args.get("includeStatic", False)),
|
|
998
|
+
after_id=after_id,
|
|
999
|
+
include_headers=bool(args.get("includeHeaders", False)),
|
|
1000
|
+
request_id=request_id,
|
|
822
1001
|
)
|
|
823
1002
|
|
|
824
1003
|
|
|
@@ -826,10 +1005,7 @@ def _capture_once(
|
|
|
826
1005
|
args: dict[str, Any],
|
|
827
1006
|
*,
|
|
828
1007
|
url: str,
|
|
829
|
-
|
|
830
|
-
entries: int,
|
|
831
|
-
include_body: bool,
|
|
832
|
-
body_chars: int,
|
|
1008
|
+
query: _NetworkQuery,
|
|
833
1009
|
) -> tuple[Any, list[dict[str, Any]]]:
|
|
834
1010
|
"""在一个临时会话里抓一次,并把这次抓取记下的网络条目一起读出来。
|
|
835
1011
|
|
|
@@ -838,10 +1014,7 @@ def _capture_once(
|
|
|
838
1014
|
|
|
839
1015
|
:param args: 协议参数
|
|
840
1016
|
:param url: 要抓的地址
|
|
841
|
-
:param
|
|
842
|
-
:param entries: 最多回多少条
|
|
843
|
-
:param include_body: 是否回传响应体
|
|
844
|
-
:param body_chars: 单条正文的字符预算
|
|
1017
|
+
:param query: 网络历史的过滤与投影参数
|
|
845
1018
|
:returns: (response, 网络条目)
|
|
846
1019
|
"""
|
|
847
1020
|
from scrapling.fetchers import StealthySession
|
|
@@ -864,13 +1037,7 @@ def _capture_once(
|
|
|
864
1037
|
try:
|
|
865
1038
|
session.start()
|
|
866
1039
|
response = session.fetch(url, **fetch_params)
|
|
867
|
-
records = _network_summary(
|
|
868
|
-
session.network,
|
|
869
|
-
pattern=pattern,
|
|
870
|
-
limit=entries,
|
|
871
|
-
include_body=include_body,
|
|
872
|
-
max_body_chars=body_chars,
|
|
873
|
-
)
|
|
1040
|
+
records = _network_summary(session.network, query=query)
|
|
874
1041
|
finally:
|
|
875
1042
|
# 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
|
|
876
1043
|
with contextlib.suppress(Exception):
|
|
@@ -893,22 +1060,13 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
893
1060
|
_require(StealthyFetcher)
|
|
894
1061
|
url = _url(args)
|
|
895
1062
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
896
|
-
|
|
1063
|
+
query = _network_read(args)
|
|
897
1064
|
|
|
898
1065
|
# 整条链路投到一条专属线程上:patchright 的同步 API 与创建它的线程绑定(greenlet),
|
|
899
1066
|
# 而 bridge 的 worker 线程是「谁抢到帧谁处理」,所以这里建一条自己的、用完就收。
|
|
900
1067
|
worker = _SessionWorker()
|
|
901
1068
|
try:
|
|
902
|
-
response, records = worker.run(
|
|
903
|
-
lambda: _capture_once(
|
|
904
|
-
args,
|
|
905
|
-
url=url,
|
|
906
|
-
pattern=pattern,
|
|
907
|
-
entries=entries,
|
|
908
|
-
include_body=include_body,
|
|
909
|
-
body_chars=body_chars,
|
|
910
|
-
)
|
|
911
|
-
)
|
|
1069
|
+
response, records = worker.run(lambda: _capture_once(args, url=url, query=query))
|
|
912
1070
|
finally:
|
|
913
1071
|
worker.stop()
|
|
914
1072
|
|
|
@@ -919,13 +1077,18 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
919
1077
|
main_content_only=main_content_only,
|
|
920
1078
|
max_content_chars=limit,
|
|
921
1079
|
strip_inline_images=_strip_inline_images(args),
|
|
1080
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
922
1081
|
)
|
|
923
1082
|
payload["xhr"] = records
|
|
924
1083
|
return payload
|
|
925
1084
|
|
|
926
1085
|
|
|
927
1086
|
def _fake_response(html: str, url: str, status: int) -> Any:
|
|
928
|
-
"""造一个不带网络的 ``Response
|
|
1087
|
+
"""造一个不带网络的 ``Response``,让已有 HTML 走与抓取同一条归一管线。
|
|
1088
|
+
|
|
1089
|
+
调用方是 :mod:`session_page`(读会话当前页的 DOM)与测试夹具:正文清洗与截断只写在
|
|
1090
|
+
:func:`to_payload` 一处,离线进来的 HTML 不许绕过它。
|
|
1091
|
+
"""
|
|
929
1092
|
from scrapling.engines.toolbelt.custom import Response
|
|
930
1093
|
|
|
931
1094
|
return Response(
|
|
@@ -939,45 +1102,33 @@ def _fake_response(html: str, url: str, status: int) -> Any:
|
|
|
939
1102
|
)
|
|
940
1103
|
|
|
941
1104
|
|
|
942
|
-
def
|
|
943
|
-
"""
|
|
1105
|
+
def _adaptive_kwargs(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
1106
|
+
"""按部署表态给出 adaptive 指纹库的 storage 与 storage_args。
|
|
944
1107
|
|
|
945
|
-
|
|
946
|
-
|
|
1108
|
+
``deployment.adaptiveStorage`` 只认 ``sqlite``(默认)与 ``redis``;Redis 那一支把连接
|
|
1109
|
+
串与按注册域分桶的 ``url`` 一起交给 ``RedisStorageSystem``,客户端不可达时翻成带码的
|
|
1110
|
+
``ADAPTIVE_STORAGE_UNAVAILABLE``,而不是让整次抽取以裸异常收场。
|
|
947
1111
|
"""
|
|
948
|
-
|
|
949
|
-
if
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
if
|
|
954
|
-
raise AdapterError("BAD_ARGS", "
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
css_selector=css_selector,
|
|
960
|
-
main_content_only=main_content_only,
|
|
961
|
-
max_content_chars=limit,
|
|
962
|
-
strip_inline_images=_strip_inline_images(args),
|
|
963
|
-
)
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
967
|
-
"""对已有 HTML 做 CSS/XPath 选择,返回命中的文本与少量属性。
|
|
1112
|
+
deployment = args.get("deployment")
|
|
1113
|
+
settings = deployment if isinstance(deployment, dict) else {}
|
|
1114
|
+
backend = settings.get("adaptiveStorage")
|
|
1115
|
+
if backend is None or backend == "sqlite":
|
|
1116
|
+
return {"storage_args": {"storage_file": ADAPTIVE_STORAGE_FILE, "url": url}}
|
|
1117
|
+
if backend != "redis":
|
|
1118
|
+
raise AdapterError("BAD_ARGS", f"unknown adaptiveStorage: {backend}")
|
|
1119
|
+
redis_url = settings.get("redisUrl")
|
|
1120
|
+
if redis_url is not None and not isinstance(redis_url, str):
|
|
1121
|
+
raise AdapterError("BAD_ARGS", "redisUrl must be a string")
|
|
1122
|
+
from redis_storage import DEFAULT_REDIS_URL, RedisStorageSystem
|
|
968
1123
|
|
|
969
|
-
|
|
970
|
-
|
|
1124
|
+
return {
|
|
1125
|
+
"storage": RedisStorageSystem,
|
|
1126
|
+
"storage_args": {"redis_url": redis_url or DEFAULT_REDIS_URL, "url": url},
|
|
1127
|
+
}
|
|
971
1128
|
|
|
972
|
-
``adaptive`` 打开时走 Scrapling 的自愈选择器:命中成功就把首个元素的指纹存库,
|
|
973
|
-
站点改版后同一个选择器直接命中失败时,按指纹重定位。存储文件固定在 sidecar 的
|
|
974
|
-
工作目录(部署侧的 ``dataDir``),键按 ``url`` 的注册域分桶 —— 所以重定位还要求
|
|
975
|
-
给 ``url``;不给就全落在 ``default`` 桶里,跨站点共用一份指纹。
|
|
976
1129
|
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
``truncated`` —— 总条数与单条长度是两根独立的轴,只压一根等于没压。
|
|
980
|
-
"""
|
|
1130
|
+
def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
1131
|
+
"""对已有 HTML 做选择,返回命中文本、属性或多字段行。"""
|
|
981
1132
|
from scrapling.parser import Selector
|
|
982
1133
|
|
|
983
1134
|
html = args.get("html")
|
|
@@ -989,35 +1140,126 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
989
1140
|
attribute = args.get("attribute")
|
|
990
1141
|
if attribute is not None and not isinstance(attribute, str):
|
|
991
1142
|
raise AdapterError("BAD_ARGS", "attribute must be a string or null")
|
|
992
|
-
adaptive = bool(args.get("adaptive", False))
|
|
993
1143
|
url = args.get("url")
|
|
994
1144
|
if url is not None and not isinstance(url, str):
|
|
995
1145
|
raise AdapterError("BAD_ARGS", "url must be a string or null")
|
|
996
1146
|
|
|
1147
|
+
use_xpath = bool(args.get("useXpath", False))
|
|
1148
|
+
query_type = args.get("queryType")
|
|
1149
|
+
if query_type is not None and not isinstance(query_type, str):
|
|
1150
|
+
raise AdapterError("BAD_ARGS", "queryType must be a string")
|
|
1151
|
+
query_type = query_type or ("xpath" if use_xpath else "css")
|
|
1152
|
+
if query_type not in ("css", "xpath", "text", "regex", "similar"):
|
|
1153
|
+
raise AdapterError("BAD_ARGS", f"unknown queryType: {query_type}")
|
|
1154
|
+
|
|
1155
|
+
adaptive_alias = bool(args.get("adaptive", False))
|
|
1156
|
+
adaptive_save = bool(args.get("adaptiveSave", False)) or adaptive_alias
|
|
1157
|
+
adaptive_relocate = bool(args.get("adaptiveRelocate", False)) or adaptive_alias
|
|
1158
|
+
adaptive = adaptive_save or adaptive_relocate
|
|
1159
|
+
if adaptive and query_type not in ("css", "xpath"):
|
|
1160
|
+
raise AdapterError("BAD_ARGS", "adaptive currently requires queryType css or xpath")
|
|
1161
|
+
|
|
1162
|
+
identifier = args.get("identifier")
|
|
1163
|
+
if identifier is not None and not isinstance(identifier, str):
|
|
1164
|
+
raise AdapterError("BAD_ARGS", "identifier must be a string or null")
|
|
1165
|
+
percentage = args.get("percentage")
|
|
1166
|
+
if percentage is not None and (
|
|
1167
|
+
not isinstance(percentage, int) or isinstance(percentage, bool) or not 1 <= percentage <= 100
|
|
1168
|
+
):
|
|
1169
|
+
raise AdapterError("BAD_ARGS", "percentage must be an integer between 1 and 100")
|
|
1170
|
+
similarity_threshold = args.get("similarityThreshold")
|
|
1171
|
+
if similarity_threshold is not None and (
|
|
1172
|
+
not isinstance(similarity_threshold, (int, float))
|
|
1173
|
+
or isinstance(similarity_threshold, bool)
|
|
1174
|
+
or not 0 <= similarity_threshold <= 1
|
|
1175
|
+
):
|
|
1176
|
+
raise AdapterError("BAD_ARGS", "similarityThreshold must be a number between 0 and 1")
|
|
1177
|
+
ignore_attributes = args.get("ignoreAttributes")
|
|
1178
|
+
if ignore_attributes is None:
|
|
1179
|
+
ignore_attributes = ("href", "src")
|
|
1180
|
+
elif not isinstance(ignore_attributes, (list, tuple)) or not all(
|
|
1181
|
+
isinstance(item, str) for item in ignore_attributes
|
|
1182
|
+
):
|
|
1183
|
+
raise AdapterError("BAD_ARGS", "ignoreAttributes must be an array of strings")
|
|
1184
|
+
|
|
1185
|
+
def query_nodes(target: Any, *, use_adaptive: bool) -> tuple[Any, str]:
|
|
1186
|
+
"""在给好的 Selector 上跑一次查询;``use_adaptive`` 决定带不带指纹参数。
|
|
1187
|
+
|
|
1188
|
+
降级路径要能拿**同一个**查询再跑一遍,所以查询本身收进闭包:自适应与普通两条路
|
|
1189
|
+
必须跑的是同一套 rules,否则「降级」会悄悄改变语义。
|
|
1190
|
+
"""
|
|
1191
|
+
if query_type in ("css", "xpath"):
|
|
1192
|
+
method = target.xpath if query_type == "xpath" else target.css
|
|
1193
|
+
selected = method(
|
|
1194
|
+
selector,
|
|
1195
|
+
identifier=identifier or "",
|
|
1196
|
+
adaptive=adaptive_relocate if use_adaptive else False,
|
|
1197
|
+
auto_save=adaptive_save if use_adaptive else False,
|
|
1198
|
+
percentage=percentage if percentage is not None else 40,
|
|
1199
|
+
)
|
|
1200
|
+
return selected, ""
|
|
1201
|
+
found, user_notice = extraction.query_nodes(
|
|
1202
|
+
target,
|
|
1203
|
+
selector,
|
|
1204
|
+
query_type,
|
|
1205
|
+
use_xpath=use_xpath,
|
|
1206
|
+
partial=bool(args.get("partial", False)),
|
|
1207
|
+
case_sensitive=bool(args.get("caseSensitive", False)),
|
|
1208
|
+
clean_match=bool(args.get("cleanMatch", True)),
|
|
1209
|
+
similarity_threshold=float(similarity_threshold) if similarity_threshold is not None else 0.2,
|
|
1210
|
+
ignore_attributes=ignore_attributes,
|
|
1211
|
+
match_text=bool(args.get("matchText", False)),
|
|
1212
|
+
)
|
|
1213
|
+
return found, user_notice
|
|
1214
|
+
|
|
1215
|
+
notice = ""
|
|
997
1216
|
if adaptive:
|
|
998
1217
|
# storage_args 必须把 url 一起带上:Scrapling 对「给了部分 storage_args」是整体
|
|
999
1218
|
# 替换而不是补齐,漏了 url 全部指纹都会落进 default 桶。url 为空时也显式传空串,
|
|
1000
1219
|
# 存储层把它归入 default 桶(StorageSystemMixin 对空值有兜底)。
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1220
|
+
#
|
|
1221
|
+
# spec §7.2 / §12.2:存储故障**不使抽取失败** —— 降级为不带 adaptive 的普通
|
|
1222
|
+
# Selector 再抽一次,正文照常返回,notice 带 ADAPTIVE_STORAGE_FAILED 与原因。
|
|
1223
|
+
# sqlite 与 redis 两侧同解:指纹库坏了不该让模型连正文都拿不到。
|
|
1224
|
+
try:
|
|
1225
|
+
page = Selector(html, url=url or "", adaptive=True, **_adaptive_kwargs(args, url or ""))
|
|
1226
|
+
nodes, notice = query_nodes(page, use_adaptive=True)
|
|
1227
|
+
except AdapterError:
|
|
1228
|
+
raise
|
|
1229
|
+
except Exception as error: # noqa: BLE001 —— 存储后端的异常类型由它自己决定
|
|
1230
|
+
page = Selector(html, url=url or "")
|
|
1231
|
+
nodes, notice = query_nodes(page, use_adaptive=False)
|
|
1232
|
+
notice = f"ADAPTIVE_STORAGE_FAILED: {type(error).__name__}: {error}"
|
|
1007
1233
|
else:
|
|
1008
|
-
page = Selector(html)
|
|
1234
|
+
page = Selector(html, url=url or "")
|
|
1235
|
+
nodes, notice = query_nodes(page, use_adaptive=False)
|
|
1009
1236
|
|
|
1010
|
-
# 命中成功时 auto_save 存指纹,命中失败且 adaptive 打开时按存过的指纹重定位 ——
|
|
1011
|
-
# 两个开关都必须在**调用**上再打开一次:Scrapling 的 adaptive 是构造器与调用两级
|
|
1012
|
-
# 开关,只开构造器的话,重定位会被静默跳过。
|
|
1013
|
-
use_xpath = bool(args.get("useXpath", False))
|
|
1014
|
-
if use_xpath:
|
|
1015
|
-
nodes = page.xpath(selector, adaptive=adaptive, auto_save=adaptive)
|
|
1016
|
-
else:
|
|
1017
|
-
nodes = page.css(selector, adaptive=adaptive, auto_save=adaptive)
|
|
1018
1237
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
1019
1238
|
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
1020
1239
|
include_attributes = bool(args.get("includeAttributes", False))
|
|
1240
|
+
include_html = bool(args.get("includeHtml", False))
|
|
1241
|
+
resolve_urls = bool(args.get("resolveUrls", False))
|
|
1242
|
+
fields = args.get("fields")
|
|
1243
|
+
|
|
1244
|
+
if fields is not None:
|
|
1245
|
+
if not isinstance(fields, dict):
|
|
1246
|
+
raise AdapterError("BAD_ARGS", "fields must be an object or null")
|
|
1247
|
+
try:
|
|
1248
|
+
rows, fields_truncated = extraction.collect_fields(
|
|
1249
|
+
list(nodes)[:limit],
|
|
1250
|
+
fields,
|
|
1251
|
+
page=page,
|
|
1252
|
+
max_content_chars=budget,
|
|
1253
|
+
resolve_urls=resolve_urls,
|
|
1254
|
+
)
|
|
1255
|
+
except ValueError as error:
|
|
1256
|
+
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1257
|
+
return {
|
|
1258
|
+
"count": len(nodes),
|
|
1259
|
+
"truncated": fields_truncated or len(nodes) > limit,
|
|
1260
|
+
"rows": _jsonable(rows),
|
|
1261
|
+
"notice": notice,
|
|
1262
|
+
}
|
|
1021
1263
|
|
|
1022
1264
|
matches: list[dict[str, Any]] = []
|
|
1023
1265
|
spent = 0
|
|
@@ -1025,18 +1267,24 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1025
1267
|
for node in nodes:
|
|
1026
1268
|
if len(matches) >= limit:
|
|
1027
1269
|
break
|
|
1028
|
-
item
|
|
1270
|
+
item = extraction.serialize_match(
|
|
1271
|
+
node,
|
|
1272
|
+
page=page,
|
|
1273
|
+
attribute=attribute,
|
|
1274
|
+
include_attributes=include_attributes,
|
|
1275
|
+
include_html=include_html,
|
|
1276
|
+
resolve_urls=resolve_urls,
|
|
1277
|
+
)
|
|
1029
1278
|
field = "value" if attribute else "text"
|
|
1030
|
-
|
|
1031
|
-
if include_attributes:
|
|
1032
|
-
item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
|
|
1279
|
+
value = str(item.get(field, ""))
|
|
1033
1280
|
# 先按剩余额度截再计入已花:一条超长正文不该把整份预算吃光,也不该在预算只剩
|
|
1034
1281
|
# 一位时还能整条通过。
|
|
1035
1282
|
room = max(0, budget - spent)
|
|
1036
|
-
if len(
|
|
1037
|
-
|
|
1283
|
+
if len(value) > room:
|
|
1284
|
+
value = value[:room]
|
|
1038
1285
|
clipped = True
|
|
1039
|
-
|
|
1286
|
+
item[field] = value
|
|
1287
|
+
spent += len(value)
|
|
1040
1288
|
matches.append(item)
|
|
1041
1289
|
if spent >= budget:
|
|
1042
1290
|
clipped = True
|
|
@@ -1045,6 +1293,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1045
1293
|
"count": len(nodes),
|
|
1046
1294
|
"truncated": clipped or len(nodes) > len(matches),
|
|
1047
1295
|
"matches": _jsonable(matches),
|
|
1296
|
+
"notice": notice,
|
|
1048
1297
|
}
|
|
1049
1298
|
|
|
1050
1299
|
|
|
@@ -1095,6 +1344,21 @@ def _probe_browser(module_name: str) -> bool:
|
|
|
1095
1344
|
return True
|
|
1096
1345
|
|
|
1097
1346
|
|
|
1347
|
+
def _websocket_guard_capability() -> bool:
|
|
1348
|
+
"""不启浏览器就判断 WebSocket 握手拦不拦得住。
|
|
1349
|
+
|
|
1350
|
+
``route_web_socket`` 挂在 Page 类上而不是实例上,所以握手那一刻就能答,不必等第一
|
|
1351
|
+
个页面建起来 —— 而 README 承诺的正是「能力报告里如实标出覆盖面」。
|
|
1352
|
+
|
|
1353
|
+
:returns: 当前安装的 patchright 是否支持拦截 WebSocket 握手(缺包算不支持)
|
|
1354
|
+
"""
|
|
1355
|
+
try:
|
|
1356
|
+
from patchright.sync_api import Page
|
|
1357
|
+
except ImportError:
|
|
1358
|
+
return False
|
|
1359
|
+
return guard.websocket_guard_supported(Page)
|
|
1360
|
+
|
|
1361
|
+
|
|
1098
1362
|
def capabilities() -> dict[str, Any]:
|
|
1099
1363
|
"""报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
|
|
1100
1364
|
report: dict[str, Any] = {
|
|
@@ -1112,20 +1376,46 @@ def capabilities() -> dict[str, Any]:
|
|
|
1112
1376
|
# 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
|
|
1113
1377
|
# 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的口径已经没有第二个引擎可标。
|
|
1114
1378
|
report["browser"] = _probe_browser("patchright.sync_api")
|
|
1379
|
+
# 浏览器守卫覆盖面的那一半(WebSocket 握手)在这里报出:拦不住时 install 只会往 stderr
|
|
1380
|
+
# 记一行,而那要等第一个页面建起来才看得见 —— 排障的人得在装载阶段就知道。
|
|
1381
|
+
report["websocketGuard"] = _websocket_guard_capability()
|
|
1115
1382
|
# 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
|
|
1116
1383
|
# server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
|
|
1117
1384
|
report["proxy"] = guard.proxy_settings()
|
|
1118
1385
|
return report
|
|
1119
1386
|
|
|
1120
1387
|
|
|
1388
|
+
def _wrap_extraction(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1389
|
+
"""把 extraction 的 ValueError 归成协议里的 BAD_ARGS。"""
|
|
1390
|
+
try:
|
|
1391
|
+
return fn(args)
|
|
1392
|
+
except ValueError as error:
|
|
1393
|
+
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1394
|
+
|
|
1395
|
+
|
|
1396
|
+
def _wrap_search(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1397
|
+
"""把 SearchError 的码原样转成协议错误。"""
|
|
1398
|
+
try:
|
|
1399
|
+
return fn(args)
|
|
1400
|
+
except search.SearchError as error:
|
|
1401
|
+
raise AdapterError(error.code, str(error)) from error
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
def search_discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
1405
|
+
"""协议入口:检索发现。"""
|
|
1406
|
+
return _wrap_search(search.discover, args)
|
|
1407
|
+
|
|
1408
|
+
|
|
1121
1409
|
METHODS = {
|
|
1122
1410
|
"ping": lambda _args: {"pong": True},
|
|
1123
1411
|
"capabilities": lambda _args: capabilities(),
|
|
1124
1412
|
"fetch": fetch,
|
|
1125
1413
|
"render": render,
|
|
1126
1414
|
"capture": capture,
|
|
1127
|
-
"extract": extract,
|
|
1128
1415
|
"select": select,
|
|
1416
|
+
"locate": lambda args: _wrap_extraction(extraction.locate, args),
|
|
1417
|
+
"links": lambda args: _wrap_extraction(extraction.links, args),
|
|
1418
|
+
"search.discover": search_discover,
|
|
1129
1419
|
}
|
|
1130
1420
|
|
|
1131
1421
|
|
|
@@ -1239,6 +1529,10 @@ class _SessionWorker:
|
|
|
1239
1529
|
self._jobs.put(None)
|
|
1240
1530
|
self._thread.join(timeout=5.0)
|
|
1241
1531
|
|
|
1532
|
+
def alive(self) -> bool:
|
|
1533
|
+
"""属主线程是否还在跑(T10 的 ``alive`` 判据:只读,不改动任何状态)。"""
|
|
1534
|
+
return not self._closed.is_set() and self._thread.is_alive()
|
|
1535
|
+
|
|
1242
1536
|
|
|
1243
1537
|
def _new_session_id() -> str:
|
|
1244
1538
|
"""生成一个短的会话 id。
|
|
@@ -1388,6 +1682,9 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1388
1682
|
"closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
|
|
1389
1683
|
"type": kind,
|
|
1390
1684
|
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
1685
|
+
# T10 的非敏感设置摘要:在开场时把生效值记下来,session.list 不必回头去
|
|
1686
|
+
# 猜(凭据面永远不进这份摘要)。
|
|
1687
|
+
"settings": _session_settings(kind, args),
|
|
1391
1688
|
# 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
|
|
1392
1689
|
"lock": entry_lock,
|
|
1393
1690
|
# browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
|
|
@@ -1445,6 +1742,9 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1445
1742
|
session = entry["session"]
|
|
1446
1743
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1447
1744
|
url = _url(args)
|
|
1745
|
+
# 这两枚在载荷阶段才用到;提前读一次,让协议对表看到它们不是死键。
|
|
1746
|
+
strip_inline_images = _strip_inline_images(args)
|
|
1747
|
+
include_metadata = bool(args.get("includeMetadata", False))
|
|
1448
1748
|
|
|
1449
1749
|
# 一份会话同一时刻只服务一个请求:static 靠 entry 锁,浏览器会话靠属主线程天然串行。
|
|
1450
1750
|
# 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
|
|
@@ -1458,7 +1758,27 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1458
1758
|
allowed, reason = guard.url_allowed(url)
|
|
1459
1759
|
if not allowed:
|
|
1460
1760
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
1461
|
-
|
|
1761
|
+
# form/json 是 POST 的请求体:没有写方法表态时按写意图拒绝,而不是把
|
|
1762
|
+
# 它们塞进一次 GET(那会变成「发出去但语义错了」,比报错更难查)。
|
|
1763
|
+
write_body = args.get("form") is not None or args.get("json") is not None
|
|
1764
|
+
static_method = "POST" if write_body else "GET"
|
|
1765
|
+
if static_method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
1766
|
+
raise AdapterError(
|
|
1767
|
+
"WRITE_DISABLED",
|
|
1768
|
+
"form/json change the request into POST; the deployment must set "
|
|
1769
|
+
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
1770
|
+
)
|
|
1771
|
+
static_params = _static_params(args, url)
|
|
1772
|
+
# extraHeaders 在浏览器那条路是请求头(上游的 extra_headers),static 这条路
|
|
1773
|
+
# 没有同名旋钮 —— 不合并的话它会被静默丢掉:调用成功、对端却没收到那个头。
|
|
1774
|
+
# 同名键以 extraHeaders 为准(它比 headers 更具体,也是浏览器侧的语义)。
|
|
1775
|
+
extra_headers = _string_map(args.get("extraHeaders"), "extraHeaders")
|
|
1776
|
+
if extra_headers is not None:
|
|
1777
|
+
merged = dict(static_params.get("headers") or {})
|
|
1778
|
+
merged.update(extra_headers)
|
|
1779
|
+
static_params["headers"] = merged
|
|
1780
|
+
static_params.update(_static_request_payload(args, static_method))
|
|
1781
|
+
response = getattr(session, static_method.lower())(url, **static_params)
|
|
1462
1782
|
else:
|
|
1463
1783
|
# 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
|
|
1464
1784
|
# 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
|
|
@@ -1480,7 +1800,14 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1480
1800
|
#
|
|
1481
1801
|
# 空的没给(`{}` / `[]` / null)不算写意图:模型「不带任何请求头」时传的就是空表,
|
|
1482
1802
|
# 为它报一条错等于把一个无害的调用说成非法。
|
|
1483
|
-
for key, hint in (
|
|
1803
|
+
for key, hint in (
|
|
1804
|
+
("headers", "extraHeaders"),
|
|
1805
|
+
("retries", "scrapling_session_open"),
|
|
1806
|
+
("cookies", "scrapling_session_open"),
|
|
1807
|
+
("params", "a static session"),
|
|
1808
|
+
("form", "a static session"),
|
|
1809
|
+
("json", "a static session"),
|
|
1810
|
+
):
|
|
1484
1811
|
if args.get(key) not in (None, {}, []):
|
|
1485
1812
|
raise AdapterError(
|
|
1486
1813
|
"BAD_ARGS",
|
|
@@ -1503,30 +1830,192 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1503
1830
|
css_selector=css_selector,
|
|
1504
1831
|
main_content_only=main_content_only,
|
|
1505
1832
|
max_content_chars=limit,
|
|
1506
|
-
strip_inline_images=
|
|
1833
|
+
strip_inline_images=strip_inline_images,
|
|
1834
|
+
include_metadata=include_metadata,
|
|
1507
1835
|
)
|
|
1508
1836
|
payload["sessionId"] = args.get("sessionId")
|
|
1509
1837
|
return payload
|
|
1510
1838
|
|
|
1511
1839
|
|
|
1840
|
+
def session_read(args: dict[str, Any]) -> dict[str, Any]:
|
|
1841
|
+
"""读浏览器会话当前页的正文,不再发一次请求。"""
|
|
1842
|
+
entry = _get_session(args.get("sessionId"))
|
|
1843
|
+
if entry["type"] == "static":
|
|
1844
|
+
raise AdapterError("BAD_ARGS", "only browser sessions keep a current page")
|
|
1845
|
+
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1846
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1847
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1848
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1849
|
+
from session_page import read_current_page
|
|
1850
|
+
|
|
1851
|
+
return worker.run(
|
|
1852
|
+
lambda: read_current_page(
|
|
1853
|
+
entry["session"],
|
|
1854
|
+
extraction_type=extraction_type,
|
|
1855
|
+
css_selector=css_selector,
|
|
1856
|
+
main_content_only=main_content_only,
|
|
1857
|
+
max_content_chars=limit,
|
|
1858
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
1859
|
+
strip_inline_images=_strip_inline_images(args),
|
|
1860
|
+
)
|
|
1861
|
+
)
|
|
1862
|
+
|
|
1863
|
+
|
|
1864
|
+
def session_act(args: dict[str, Any]) -> dict[str, Any]:
|
|
1865
|
+
"""在一个浏览器会话的当前页上执行结构化动作。"""
|
|
1866
|
+
if not guard.ALLOW_BROWSER_ACTIONS:
|
|
1867
|
+
raise AdapterError(
|
|
1868
|
+
"ACTION_DISABLED",
|
|
1869
|
+
f"browser actions are disabled; the deployment must set {guard.ALLOW_BROWSER_ACTIONS_ENV}",
|
|
1870
|
+
)
|
|
1871
|
+
entry = _get_session(args.get("sessionId"))
|
|
1872
|
+
if entry["type"] == "static":
|
|
1873
|
+
raise AdapterError("BAD_ARGS", "only browser sessions support actions")
|
|
1874
|
+
max_actions = _positive_int(args.get("maxActions"), "maxActions", 20)
|
|
1875
|
+
if max_actions > 50:
|
|
1876
|
+
raise AdapterError("BAD_ARGS", "maxActions cannot exceed 50")
|
|
1877
|
+
timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
|
|
1878
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1879
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1880
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1881
|
+
from session_page import run_actions
|
|
1882
|
+
|
|
1883
|
+
return worker.run(
|
|
1884
|
+
lambda: run_actions(
|
|
1885
|
+
entry["session"],
|
|
1886
|
+
actions=args.get("actions"),
|
|
1887
|
+
slowly=args.get("slowly") is True,
|
|
1888
|
+
max_actions=max_actions,
|
|
1889
|
+
timeout_ms=timeout_ms,
|
|
1890
|
+
)
|
|
1891
|
+
)
|
|
1892
|
+
|
|
1893
|
+
|
|
1894
|
+
def download(args: dict[str, Any]) -> dict[str, Any]:
|
|
1895
|
+
"""受门禁保护的下载入口。"""
|
|
1896
|
+
return media.download(args)
|
|
1897
|
+
|
|
1898
|
+
|
|
1899
|
+
def screenshot(args: dict[str, Any]) -> dict[str, Any]:
|
|
1900
|
+
"""截当前会话页;不会新建浏览器。"""
|
|
1901
|
+
entry = _get_session(args.get("sessionId"))
|
|
1902
|
+
if entry["type"] == "static":
|
|
1903
|
+
raise AdapterError("BAD_ARGS", "only browser sessions can take screenshots")
|
|
1904
|
+
image_type = args.get("imageType", "png")
|
|
1905
|
+
if not isinstance(image_type, str):
|
|
1906
|
+
raise AdapterError("BAD_ARGS", "imageType must be a string")
|
|
1907
|
+
selector = args.get("selector")
|
|
1908
|
+
if selector is not None and not isinstance(selector, str):
|
|
1909
|
+
raise AdapterError("BAD_ARGS", "selector must be a string or null")
|
|
1910
|
+
quality = args.get("quality")
|
|
1911
|
+
timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
|
|
1912
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1913
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1914
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1915
|
+
return worker.run(
|
|
1916
|
+
lambda: media.screenshot(
|
|
1917
|
+
entry["session"],
|
|
1918
|
+
image_type=image_type,
|
|
1919
|
+
full_page=args.get("fullPage") is True,
|
|
1920
|
+
quality=quality,
|
|
1921
|
+
selector=selector,
|
|
1922
|
+
timeout_ms=timeout_ms,
|
|
1923
|
+
)
|
|
1924
|
+
)
|
|
1925
|
+
|
|
1926
|
+
|
|
1927
|
+
def _session_settings(kind: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
1928
|
+
"""会话的非敏感设置摘要(T10)。
|
|
1929
|
+
|
|
1930
|
+
只收「这次会话是怎么配的」的开关,绝不包含 cookies、代理凭据或任何 key —— 这份
|
|
1931
|
+
摘要会被模型读到。静态会话没有浏览器那一组开关,逐项给 null。
|
|
1932
|
+
|
|
1933
|
+
:param kind: 会话类型
|
|
1934
|
+
:param args: session.open 的协议参数
|
|
1935
|
+
:returns: 可 JSON 序列化的摘要
|
|
1936
|
+
"""
|
|
1937
|
+
deployment = args.get("deployment")
|
|
1938
|
+
knobs = deployment if isinstance(deployment, dict) else {}
|
|
1939
|
+
browser = kind != "static"
|
|
1940
|
+
headless = args.get("headless", True)
|
|
1941
|
+
locale = args.get("locale")
|
|
1942
|
+
timezone_id = args.get("timezoneId")
|
|
1943
|
+
recorded = browser and (args.get("recordNetwork") is True or _knob_value(bool, knobs.get("recordRequests")) is True)
|
|
1944
|
+
return {
|
|
1945
|
+
"type": kind,
|
|
1946
|
+
"headless": bool(headless) if browser else None,
|
|
1947
|
+
"recordNetwork": recorded,
|
|
1948
|
+
"maxRecordedRequests": _knob_value(int, knobs.get("maxRecordedRequests")),
|
|
1949
|
+
"locale": locale if isinstance(locale, str) and locale else None,
|
|
1950
|
+
"timezone": timezone_id if isinstance(timezone_id, str) and timezone_id else None,
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
|
|
1954
|
+
def _session_alive(entry: dict[str, Any]) -> bool:
|
|
1955
|
+
"""会话是否还能用:构造中的占位不算,浏览器会话还要属主线程活着。
|
|
1956
|
+
|
|
1957
|
+
:param entry: 登记条目
|
|
1958
|
+
:returns: 是否可用
|
|
1959
|
+
"""
|
|
1960
|
+
if entry.get("pending") is True:
|
|
1961
|
+
return False
|
|
1962
|
+
worker = entry.get("worker")
|
|
1963
|
+
if worker is not None:
|
|
1964
|
+
return worker.alive() is True
|
|
1965
|
+
return entry.get("session") is not None
|
|
1966
|
+
|
|
1967
|
+
|
|
1968
|
+
def _pool_stats(entry: dict[str, Any]) -> dict[str, int] | None:
|
|
1969
|
+
"""浏览器会话的页池统计;没有这条能力或取不到时给 None(绝不抛)。
|
|
1970
|
+
|
|
1971
|
+
T10 的 ``poolStats`` 是可选字段:一只已经跑完开始收尾的会话也可能在取统计的一瞬
|
|
1972
|
+
出错,那不该把整个 session.list 变成一次失败。
|
|
1973
|
+
|
|
1974
|
+
:param entry: 登记条目
|
|
1975
|
+
:returns: 页池统计,或 None
|
|
1976
|
+
"""
|
|
1977
|
+
if entry.get("type") == "static":
|
|
1978
|
+
return None
|
|
1979
|
+
session = entry.get("session")
|
|
1980
|
+
getter = getattr(session, "get_pool_stats", None)
|
|
1981
|
+
if not callable(getter):
|
|
1982
|
+
return None
|
|
1983
|
+
try:
|
|
1984
|
+
stats = getter()
|
|
1985
|
+
except Exception: # noqa: BLE001 —— T10:统计拿不到时省略,不许让 list 整体失败
|
|
1986
|
+
return None
|
|
1987
|
+
if not isinstance(stats, dict):
|
|
1988
|
+
return None
|
|
1989
|
+
return {str(key): value for key, value in stats.items() if isinstance(value, int) and not isinstance(value, bool)}
|
|
1990
|
+
|
|
1991
|
+
|
|
1512
1992
|
def session_list(_args: dict[str, Any]) -> dict[str, Any]:
|
|
1513
1993
|
"""列出当前所有会话(不含任何凭据)。
|
|
1514
1994
|
|
|
1995
|
+
每行除 id / type / createdAt 之外还带 ``alive``、``settings``(非敏感设置摘要)与
|
|
1996
|
+
``poolStats``(浏览器会话取得到页池统计时才给;取不到就省略,绝不因此让 list 失败)。
|
|
1997
|
+
|
|
1515
1998
|
:param _args: 协议参数,本方法不用
|
|
1516
1999
|
:returns: 会话列表
|
|
1517
2000
|
"""
|
|
1518
2001
|
# 字典遍历期间被别的线程插入/删除会抛 RuntimeError,而那正是 bridge 多 worker 下的
|
|
1519
2002
|
# 常态。进锁里把清单复制出来,遍历就与并发改写无关。
|
|
1520
2003
|
with _SESSION_LOCK:
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
2004
|
+
entries = list(_SESSIONS.items())
|
|
2005
|
+
rows: list[dict[str, Any]] = []
|
|
2006
|
+
for session_id, entry in entries:
|
|
2007
|
+
row: dict[str, Any] = {
|
|
2008
|
+
"sessionId": session_id,
|
|
2009
|
+
"sessionType": entry["type"],
|
|
2010
|
+
# 构造中的条目还没有创建时间;报空串而不是 KeyError。
|
|
2011
|
+
"createdAt": entry.get("created_at", ""),
|
|
2012
|
+
"alive": _session_alive(entry),
|
|
2013
|
+
"settings": entry.get("settings") or _session_settings(str(entry.get("type", "")), {}),
|
|
2014
|
+
}
|
|
2015
|
+
stats = _pool_stats(entry)
|
|
2016
|
+
if stats is not None:
|
|
2017
|
+
row["poolStats"] = stats
|
|
2018
|
+
rows.append(row)
|
|
1530
2019
|
return {"sessions": rows}
|
|
1531
2020
|
|
|
1532
2021
|
|
|
@@ -1604,7 +2093,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1604
2093
|
entry = _get_session(session_id)
|
|
1605
2094
|
if entry["type"] == "static":
|
|
1606
2095
|
raise AdapterError("BAD_ARGS", "static sessions keep no network history")
|
|
1607
|
-
|
|
2096
|
+
query = _network_read(args)
|
|
1608
2097
|
recorder = getattr(entry["session"], "network", None)
|
|
1609
2098
|
if recorder is None or not getattr(recorder, "enabled", False):
|
|
1610
2099
|
raise AdapterError(
|
|
@@ -1615,15 +2104,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1615
2104
|
worker: _SessionWorker | None = entry["worker"]
|
|
1616
2105
|
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1617
2106
|
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1618
|
-
matches = worker.run(
|
|
1619
|
-
lambda: _network_summary(
|
|
1620
|
-
recorder,
|
|
1621
|
-
pattern=pattern,
|
|
1622
|
-
limit=entries,
|
|
1623
|
-
include_body=include_body,
|
|
1624
|
-
max_body_chars=body_chars,
|
|
1625
|
-
)
|
|
1626
|
-
)
|
|
2107
|
+
matches = worker.run(lambda: _network_summary(recorder, query=query))
|
|
1627
2108
|
return {"sessionId": session_id, "count": len(matches), "matches": matches}
|
|
1628
2109
|
|
|
1629
2110
|
|
|
@@ -1679,9 +2160,20 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
1679
2160
|
try:
|
|
1680
2161
|
if saving:
|
|
1681
2162
|
worker.run(lambda: session.save_state(target))
|
|
2163
|
+
# spec §11.6:登录态文件是凭据面(cookie / localStorage / IndexedDB),落盘后
|
|
2164
|
+
# 收到 0600。Windows 上 chmod 只动只读位,失败也不该让存取整体失败。
|
|
2165
|
+
with contextlib.suppress(OSError):
|
|
2166
|
+
Path(target).chmod(0o600)
|
|
1682
2167
|
else:
|
|
1683
2168
|
worker.run(lambda: session.load_state(target))
|
|
1684
|
-
except
|
|
2169
|
+
except FileNotFoundError as error:
|
|
2170
|
+
# 上游的原文里带着**宿主绝对路径**(「[Errno 2] No such file or directory:
|
|
2171
|
+
# '/Users/…/login.json'」):那是部署面的信息,对模型既没用又是泄露。点名
|
|
2172
|
+
# 那个模型自己给的文件名就够了。
|
|
2173
|
+
raise AdapterError("STATE_FAILED", f"state file does not exist: {Path(target).name}") from error
|
|
2174
|
+
except json.JSONDecodeError as error:
|
|
2175
|
+
raise AdapterError("STATE_FAILED", f"state file is not valid JSON: {Path(target).name}") from error
|
|
2176
|
+
except Exception as error: # 上游的其余文件/JSON 错误一律翻成可路由的码
|
|
1685
2177
|
raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1686
2178
|
return {"sessionId": session_id, "path": target, "saved": saving}
|
|
1687
2179
|
|
|
@@ -1723,6 +2215,10 @@ METHODS.update(
|
|
|
1723
2215
|
"session.list": session_list,
|
|
1724
2216
|
"session.close": session_close,
|
|
1725
2217
|
"session.network": session_network,
|
|
2218
|
+
"session.read": session_read,
|
|
2219
|
+
"session.act": session_act,
|
|
2220
|
+
"download": download,
|
|
2221
|
+
"screenshot": screenshot,
|
|
1726
2222
|
"session.state_save": session_state_save,
|
|
1727
2223
|
"session.state_load": session_state_load,
|
|
1728
2224
|
}
|