@jayyuen66/dsh-scrapling 0.1.1 → 0.1.3
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 +176 -0
- package/LICENSE +1 -1
- package/README.md +368 -549
- package/README.zh-CN.md +362 -397
- package/THIRD_PARTY_NOTICES.md +20 -2
- package/bin/dsh-scrapling.mjs +13 -0
- package/client.js +11 -1409
- package/host.js +43 -34
- package/package.json +66 -48
- package/py/adapters.py +752 -272
- package/py/bridge.py +44 -4
- package/py/crawl.py +595 -93
- package/py/extraction.py +400 -0
- package/py/guard.py +160 -34
- package/py/media.py +399 -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
|
-
"""把片段里像查询串的那一段脱敏;没有命中时原样返回。
|
|
188
|
-
|
|
189
|
-
片段有两种藏令牌的写法:OAuth2 隐式流程把整个片段当查询串(``#access_token=…``),
|
|
190
|
-
单页应用的路由则是先路径后查询(``#!/list?token=…``)。两种都要覆盖。
|
|
191
|
-
|
|
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)
|
|
151
|
+
# 查询串与 authority 的凭据脱敏在 py/redact.py:guard 的日志与网络摘要共用同一份。
|
|
199
152
|
|
|
153
|
+
_SENSITIVE_HEADERS = frozenset({"set-cookie", "cookie", "authorization", "proxy-authorization"})
|
|
200
154
|
|
|
201
|
-
def redact_url_secrets(raw: str) -> str:
|
|
202
|
-
"""把 URL 里像凭据的部分替换成占位符。
|
|
203
155
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
只按参数名判断、不看值 —— 值本身无法可靠判定(短 token 与普通 id 长得一样)。
|
|
210
|
-
认不出来的参数原样保留:把 ``?page=2`` 也涂掉只会让摘要失去意义,而那不是凭据。
|
|
211
|
-
|
|
212
|
-
:param raw: 原始 URL
|
|
213
|
-
:returns: 已脱敏的 URL;解析不出或没有可脱敏的部分时原样返回
|
|
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
|
-
network: Any, #
|
|
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
|
|
|
@@ -394,7 +344,7 @@ def drop_data_uris(text: str, *, html: bool = False) -> str:
|
|
|
394
344
|
return "\n".join(out)
|
|
395
345
|
|
|
396
346
|
|
|
397
|
-
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: #
|
|
347
|
+
def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # 同上
|
|
398
348
|
"""按 ``css_selector`` 把清洗过的树收窄成若干棵子树;没给选择器就是整棵。
|
|
399
349
|
|
|
400
350
|
口径与 Scrapling 自家 ``Convertor._extract_content`` 一致:命中 0 个元素就是空表,
|
|
@@ -411,6 +361,30 @@ def _scoped_pages(page: Any, css_selector: str | None) -> list[Any]: # noqa: AN
|
|
|
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,63 @@ 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
|
+
|
|
511
599
|
def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
512
600
|
"""静态抓取(curl_cffi)。不需要浏览器。
|
|
513
601
|
|
|
@@ -518,18 +606,10 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
518
606
|
_require(Fetcher)
|
|
519
607
|
url = _url(args)
|
|
520
608
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
521
|
-
params = _static_params(args, url)
|
|
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
609
|
method = str(args.get("method", "GET")).upper()
|
|
531
610
|
if method not in ("GET", "POST", "PUT", "DELETE"):
|
|
532
611
|
raise AdapterError("BAD_ARGS", f"unsupported method: {method}")
|
|
612
|
+
request_payload = _static_request_payload(args, method)
|
|
533
613
|
if method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
534
614
|
# 这一侧是硬拒,不依赖 Host 有没有把入参摆出来:手搓一帧 stdin 也写不出去。
|
|
535
615
|
raise AdapterError(
|
|
@@ -537,15 +617,11 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
537
617
|
f"{method} changes state on the remote side; the deployment must set "
|
|
538
618
|
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
539
619
|
)
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
# 数组、数字、布尔也是合法的 JSON 请求体(curl_cffi 的 ``json=`` 照收)。此前只有
|
|
546
|
-
# dict 走 json、str 走 data,其余**静默丢弃** —— 模型发一个 `body: [1, 2]`,请求照
|
|
547
|
-
# 发、对端收到空体,而回包上没有一行能看出这件事。
|
|
548
|
-
params["json"] = _jsonable(body)
|
|
620
|
+
params = _static_params(args, url)
|
|
621
|
+
params.update(request_payload)
|
|
622
|
+
impersonate = args.get("impersonate")
|
|
623
|
+
if isinstance(impersonate, str) and impersonate:
|
|
624
|
+
params["impersonate"] = impersonate
|
|
549
625
|
|
|
550
626
|
# Host 侧闸门判过之后到 curl_cffi 真解析、真建连之间隔着一个进程边界(TOCTOU),
|
|
551
627
|
# 所以这里在发车之前用同一份 guard 复判一次 —— 浏览器路径由 page.route 逐请求兜住,
|
|
@@ -562,6 +638,7 @@ def fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
562
638
|
main_content_only=main_content_only,
|
|
563
639
|
max_content_chars=limit,
|
|
564
640
|
strip_inline_images=_strip_inline_images(args),
|
|
641
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
565
642
|
)
|
|
566
643
|
|
|
567
644
|
|
|
@@ -629,12 +706,17 @@ SESSION_ONLY_KEYS = frozenset(
|
|
|
629
706
|
"allow_webgl",
|
|
630
707
|
"block_ads",
|
|
631
708
|
"block_webrtc",
|
|
709
|
+
"blocked_domains",
|
|
632
710
|
"cdp_url",
|
|
711
|
+
"cookies",
|
|
712
|
+
"disable_resources",
|
|
633
713
|
"dns_over_https",
|
|
634
714
|
"executable_path",
|
|
715
|
+
"google_search",
|
|
635
716
|
"headless",
|
|
636
717
|
"hide_canvas",
|
|
637
718
|
"init_script",
|
|
719
|
+
"load_dom",
|
|
638
720
|
"locale",
|
|
639
721
|
"max_pages",
|
|
640
722
|
"max_recorded_requests",
|
|
@@ -645,6 +727,7 @@ SESSION_ONLY_KEYS = frozenset(
|
|
|
645
727
|
"timezone_id",
|
|
646
728
|
"useragent",
|
|
647
729
|
"user_data_dir",
|
|
730
|
+
"wait_selector_state",
|
|
648
731
|
}
|
|
649
732
|
)
|
|
650
733
|
|
|
@@ -663,7 +746,7 @@ _DEPLOYMENT_KNOBS: tuple[tuple[str, str, type], ...] = (
|
|
|
663
746
|
)
|
|
664
747
|
|
|
665
748
|
|
|
666
|
-
def _knob_value(kind: type, value: Any) -> Any: #
|
|
749
|
+
def _knob_value(kind: type, value: Any) -> Any: # 收的是部署载荷里的任意 JSON 值
|
|
667
750
|
"""按声明的类型收下一枚部署旋钮值;类型不符给 None。
|
|
668
751
|
|
|
669
752
|
类型必须真的对得上:这一层承载的是部署表态,把字符串塞进一个整数旋钮(或反过来)时
|
|
@@ -717,12 +800,30 @@ def _browser_params(args: dict[str, Any], url: str, *, level: str = "session") -
|
|
|
717
800
|
"headless": bool(args.get("headless", True)),
|
|
718
801
|
"timeout": _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS),
|
|
719
802
|
"block_ads": bool(args.get("blockAds", False)),
|
|
720
|
-
|
|
721
|
-
|
|
803
|
+
# 这里刻意**不**预置 blocked_domains / disable_resources:见上方 docstring。模型
|
|
804
|
+
# 显式给了才在下面按条件覆盖;没给就交给上游沿用会话配置。
|
|
722
805
|
}
|
|
723
806
|
proxy = guard.browser_proxy(url)
|
|
724
807
|
if proxy is not None:
|
|
725
808
|
params["proxy"] = proxy
|
|
809
|
+
cookies = _cookie_list(args.get("cookies"))
|
|
810
|
+
if cookies is not None:
|
|
811
|
+
params["cookies"] = cookies
|
|
812
|
+
blocked_domains = _string_set(args.get("blockedDomains"), "blockedDomains")
|
|
813
|
+
if blocked_domains is not None:
|
|
814
|
+
params["blocked_domains"] = blocked_domains
|
|
815
|
+
if isinstance(args.get("disableResources"), bool):
|
|
816
|
+
params["disable_resources"] = args["disableResources"]
|
|
817
|
+
if isinstance(args.get("loadDom"), bool):
|
|
818
|
+
params["load_dom"] = args["loadDom"]
|
|
819
|
+
if isinstance(args.get("googleSearch"), bool):
|
|
820
|
+
params["google_search"] = args["googleSearch"]
|
|
821
|
+
if args.get("retries") is not None:
|
|
822
|
+
params["retries"] = _bounded_int(args.get("retries"), "retries", 3, 10)
|
|
823
|
+
if args.get("retryDelay") is not None:
|
|
824
|
+
params["retry_delay"] = _positive_int(args.get("retryDelay"), "retryDelay", 1)
|
|
825
|
+
if args.get("maxPages") is not None:
|
|
826
|
+
params["max_pages"] = _bounded_int(args.get("maxPages"), "maxPages", 1, 50)
|
|
726
827
|
if args.get("networkIdle"):
|
|
727
828
|
params["network_idle"] = True
|
|
728
829
|
for key, name in (
|
|
@@ -805,20 +906,59 @@ def render(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
805
906
|
main_content_only=main_content_only,
|
|
806
907
|
max_content_chars=limit,
|
|
807
908
|
strip_inline_images=_strip_inline_images(args),
|
|
909
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
808
910
|
)
|
|
809
911
|
|
|
810
912
|
|
|
811
|
-
|
|
812
|
-
"""
|
|
913
|
+
class _NetworkQuery(NamedTuple):
|
|
914
|
+
"""一次网络历史读取的全部过滤与投影参数。"""
|
|
915
|
+
|
|
916
|
+
pattern: str | None
|
|
917
|
+
limit: int
|
|
918
|
+
include_body: bool
|
|
919
|
+
body_chars: int
|
|
920
|
+
method: str | None
|
|
921
|
+
status: int | None
|
|
922
|
+
resource_type: str | None
|
|
923
|
+
include_static: bool
|
|
924
|
+
after_id: int
|
|
925
|
+
include_headers: bool
|
|
926
|
+
request_id: int | None
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _network_read(args: dict[str, Any]) -> _NetworkQuery:
|
|
930
|
+
"""抽出「读网络历史」的过滤与投影参数并校验。
|
|
813
931
|
|
|
814
932
|
:param args: 协议参数
|
|
815
|
-
:returns:
|
|
933
|
+
:returns: 归一后的查询参数
|
|
816
934
|
"""
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
935
|
+
method = args.get("method")
|
|
936
|
+
if method is not None and (not isinstance(method, str) or not method):
|
|
937
|
+
raise AdapterError("BAD_ARGS", "method must be a non-empty string or null")
|
|
938
|
+
status = args.get("status")
|
|
939
|
+
if status is not None and (not isinstance(status, int) or isinstance(status, bool) or not 100 <= status <= 599):
|
|
940
|
+
raise AdapterError("BAD_ARGS", "status must be an integer between 100 and 599")
|
|
941
|
+
resource_type = args.get("resourceType")
|
|
942
|
+
if resource_type is not None and (not isinstance(resource_type, str) or not resource_type):
|
|
943
|
+
raise AdapterError("BAD_ARGS", "resourceType must be a non-empty string or null")
|
|
944
|
+
after_id = args.get("afterId", 0)
|
|
945
|
+
if not isinstance(after_id, int) or isinstance(after_id, bool) or after_id < 0:
|
|
946
|
+
raise AdapterError("BAD_ARGS", "afterId must be a non-negative integer")
|
|
947
|
+
request_id = args.get("requestId")
|
|
948
|
+
if request_id is not None and (not isinstance(request_id, int) or isinstance(request_id, bool) or request_id <= 0):
|
|
949
|
+
raise AdapterError("BAD_ARGS", "requestId must be a positive integer or null")
|
|
950
|
+
return _NetworkQuery(
|
|
951
|
+
pattern=_url_pattern(args),
|
|
952
|
+
limit=_positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
|
|
953
|
+
include_body=bool(args.get("includeBody", False)),
|
|
954
|
+
body_chars=_positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
|
|
955
|
+
method=method.upper() if isinstance(method, str) else None,
|
|
956
|
+
status=status,
|
|
957
|
+
resource_type=resource_type,
|
|
958
|
+
include_static=bool(args.get("includeStatic", False)),
|
|
959
|
+
after_id=after_id,
|
|
960
|
+
include_headers=bool(args.get("includeHeaders", False)),
|
|
961
|
+
request_id=request_id,
|
|
822
962
|
)
|
|
823
963
|
|
|
824
964
|
|
|
@@ -826,10 +966,7 @@ def _capture_once(
|
|
|
826
966
|
args: dict[str, Any],
|
|
827
967
|
*,
|
|
828
968
|
url: str,
|
|
829
|
-
|
|
830
|
-
entries: int,
|
|
831
|
-
include_body: bool,
|
|
832
|
-
body_chars: int,
|
|
969
|
+
query: _NetworkQuery,
|
|
833
970
|
) -> tuple[Any, list[dict[str, Any]]]:
|
|
834
971
|
"""在一个临时会话里抓一次,并把这次抓取记下的网络条目一起读出来。
|
|
835
972
|
|
|
@@ -838,15 +975,20 @@ def _capture_once(
|
|
|
838
975
|
|
|
839
976
|
:param args: 协议参数
|
|
840
977
|
:param url: 要抓的地址
|
|
841
|
-
:param
|
|
842
|
-
:param entries: 最多回多少条
|
|
843
|
-
:param include_body: 是否回传响应体
|
|
844
|
-
:param body_chars: 单条正文的字符预算
|
|
978
|
+
:param query: 网络历史的过滤与投影参数
|
|
845
979
|
:returns: (response, 网络条目)
|
|
846
980
|
"""
|
|
847
981
|
from scrapling.fetchers import StealthySession
|
|
848
982
|
|
|
849
983
|
session_params = _session_browser_params(args)
|
|
984
|
+
# 与 _make_session 对齐:浏览器会话的代理只能在构造期给,而 _session_browser_params
|
|
985
|
+
# 按 SESSION_ONLY_KEYS 把它连同 block_webrtc 一起过滤掉了。不在这里补,配了代理的
|
|
986
|
+
# 机器上这条路径的 Chromium 会直连 —— 泄露真实出口 IP,三条浏览器路径行为不一致。
|
|
987
|
+
proxy = guard.split_proxy(guard.default_proxy())
|
|
988
|
+
if proxy is not None:
|
|
989
|
+
session_params["proxy"] = proxy
|
|
990
|
+
# 走代理时强制为真,与 _make_session 同一条理由:WebRTC 泄露的是访客真实出口 IP。
|
|
991
|
+
session_params["block_webrtc"] = bool(args.get("blockWebrtc")) or proxy is not None
|
|
850
992
|
session_params["record_requests"] = True
|
|
851
993
|
fetch_params = _browser_params(args, url, level="fetch")
|
|
852
994
|
# 会话的代理在构造期就定死了,逐次 fetch 再给一次只会被上游丢掉。
|
|
@@ -856,13 +998,7 @@ def _capture_once(
|
|
|
856
998
|
try:
|
|
857
999
|
session.start()
|
|
858
1000
|
response = session.fetch(url, **fetch_params)
|
|
859
|
-
records = _network_summary(
|
|
860
|
-
session.network,
|
|
861
|
-
pattern=pattern,
|
|
862
|
-
limit=entries,
|
|
863
|
-
include_body=include_body,
|
|
864
|
-
max_body_chars=body_chars,
|
|
865
|
-
)
|
|
1001
|
+
records = _network_summary(session.network, query=query)
|
|
866
1002
|
finally:
|
|
867
1003
|
# 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
|
|
868
1004
|
with contextlib.suppress(Exception):
|
|
@@ -885,22 +1021,13 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
885
1021
|
_require(StealthyFetcher)
|
|
886
1022
|
url = _url(args)
|
|
887
1023
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
888
|
-
|
|
1024
|
+
query = _network_read(args)
|
|
889
1025
|
|
|
890
1026
|
# 整条链路投到一条专属线程上:patchright 的同步 API 与创建它的线程绑定(greenlet),
|
|
891
1027
|
# 而 bridge 的 worker 线程是「谁抢到帧谁处理」,所以这里建一条自己的、用完就收。
|
|
892
1028
|
worker = _SessionWorker()
|
|
893
1029
|
try:
|
|
894
|
-
response, records = worker.run(
|
|
895
|
-
lambda: _capture_once(
|
|
896
|
-
args,
|
|
897
|
-
url=url,
|
|
898
|
-
pattern=pattern,
|
|
899
|
-
entries=entries,
|
|
900
|
-
include_body=include_body,
|
|
901
|
-
body_chars=body_chars,
|
|
902
|
-
)
|
|
903
|
-
)
|
|
1030
|
+
response, records = worker.run(lambda: _capture_once(args, url=url, query=query))
|
|
904
1031
|
finally:
|
|
905
1032
|
worker.stop()
|
|
906
1033
|
|
|
@@ -911,13 +1038,18 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
911
1038
|
main_content_only=main_content_only,
|
|
912
1039
|
max_content_chars=limit,
|
|
913
1040
|
strip_inline_images=_strip_inline_images(args),
|
|
1041
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
914
1042
|
)
|
|
915
1043
|
payload["xhr"] = records
|
|
916
1044
|
return payload
|
|
917
1045
|
|
|
918
1046
|
|
|
919
1047
|
def _fake_response(html: str, url: str, status: int) -> Any:
|
|
920
|
-
"""造一个不带网络的 ``Response
|
|
1048
|
+
"""造一个不带网络的 ``Response``,让已有 HTML 走与抓取同一条归一管线。
|
|
1049
|
+
|
|
1050
|
+
调用方是 :mod:`session_page`(读会话当前页的 DOM)与测试夹具:正文清洗与截断只写在
|
|
1051
|
+
:func:`to_payload` 一处,离线进来的 HTML 不许绕过它。
|
|
1052
|
+
"""
|
|
921
1053
|
from scrapling.engines.toolbelt.custom import Response
|
|
922
1054
|
|
|
923
1055
|
return Response(
|
|
@@ -931,45 +1063,33 @@ def _fake_response(html: str, url: str, status: int) -> Any:
|
|
|
931
1063
|
)
|
|
932
1064
|
|
|
933
1065
|
|
|
934
|
-
def
|
|
935
|
-
"""
|
|
1066
|
+
def _adaptive_kwargs(args: dict[str, Any], url: str) -> dict[str, Any]:
|
|
1067
|
+
"""按部署表态给出 adaptive 指纹库的 storage 与 storage_args。
|
|
936
1068
|
|
|
937
|
-
|
|
938
|
-
|
|
1069
|
+
``deployment.adaptiveStorage`` 只认 ``sqlite``(默认)与 ``redis``;Redis 那一支把连接
|
|
1070
|
+
串与按注册域分桶的 ``url`` 一起交给 ``RedisStorageSystem``,客户端不可达时翻成带码的
|
|
1071
|
+
``ADAPTIVE_STORAGE_UNAVAILABLE``,而不是让整次抽取以裸异常收场。
|
|
939
1072
|
"""
|
|
940
|
-
|
|
941
|
-
if
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
if
|
|
946
|
-
raise AdapterError("BAD_ARGS", "
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
css_selector=css_selector,
|
|
952
|
-
main_content_only=main_content_only,
|
|
953
|
-
max_content_chars=limit,
|
|
954
|
-
strip_inline_images=_strip_inline_images(args),
|
|
955
|
-
)
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
959
|
-
"""对已有 HTML 做 CSS/XPath 选择,返回命中的文本与少量属性。
|
|
1073
|
+
deployment = args.get("deployment")
|
|
1074
|
+
settings = deployment if isinstance(deployment, dict) else {}
|
|
1075
|
+
backend = settings.get("adaptiveStorage")
|
|
1076
|
+
if backend is None or backend == "sqlite":
|
|
1077
|
+
return {"storage_args": {"storage_file": ADAPTIVE_STORAGE_FILE, "url": url}}
|
|
1078
|
+
if backend != "redis":
|
|
1079
|
+
raise AdapterError("BAD_ARGS", f"unknown adaptiveStorage: {backend}")
|
|
1080
|
+
redis_url = settings.get("redisUrl")
|
|
1081
|
+
if redis_url is not None and not isinstance(redis_url, str):
|
|
1082
|
+
raise AdapterError("BAD_ARGS", "redisUrl must be a string")
|
|
1083
|
+
from redis_storage import DEFAULT_REDIS_URL, RedisStorageSystem
|
|
960
1084
|
|
|
961
|
-
|
|
962
|
-
|
|
1085
|
+
return {
|
|
1086
|
+
"storage": RedisStorageSystem,
|
|
1087
|
+
"storage_args": {"redis_url": redis_url or DEFAULT_REDIS_URL, "url": url},
|
|
1088
|
+
}
|
|
963
1089
|
|
|
964
|
-
``adaptive`` 打开时走 Scrapling 的自愈选择器:命中成功就把首个元素的指纹存库,
|
|
965
|
-
站点改版后同一个选择器直接命中失败时,按指纹重定位。存储文件固定在 sidecar 的
|
|
966
|
-
工作目录(部署侧的 ``dataDir``),键按 ``url`` 的注册域分桶 —— 所以重定位还要求
|
|
967
|
-
给 ``url``;不给就全落在 ``default`` 桶里,跨站点共用一份指纹。
|
|
968
1090
|
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
``truncated`` —— 总条数与单条长度是两根独立的轴,只压一根等于没压。
|
|
972
|
-
"""
|
|
1091
|
+
def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
1092
|
+
"""对已有 HTML 做选择,返回命中文本、属性或多字段行。"""
|
|
973
1093
|
from scrapling.parser import Selector
|
|
974
1094
|
|
|
975
1095
|
html = args.get("html")
|
|
@@ -981,35 +1101,126 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
981
1101
|
attribute = args.get("attribute")
|
|
982
1102
|
if attribute is not None and not isinstance(attribute, str):
|
|
983
1103
|
raise AdapterError("BAD_ARGS", "attribute must be a string or null")
|
|
984
|
-
adaptive = bool(args.get("adaptive", False))
|
|
985
1104
|
url = args.get("url")
|
|
986
1105
|
if url is not None and not isinstance(url, str):
|
|
987
1106
|
raise AdapterError("BAD_ARGS", "url must be a string or null")
|
|
988
1107
|
|
|
1108
|
+
use_xpath = bool(args.get("useXpath", False))
|
|
1109
|
+
query_type = args.get("queryType")
|
|
1110
|
+
if query_type is not None and not isinstance(query_type, str):
|
|
1111
|
+
raise AdapterError("BAD_ARGS", "queryType must be a string")
|
|
1112
|
+
query_type = query_type or ("xpath" if use_xpath else "css")
|
|
1113
|
+
if query_type not in ("css", "xpath", "text", "regex", "similar"):
|
|
1114
|
+
raise AdapterError("BAD_ARGS", f"unknown queryType: {query_type}")
|
|
1115
|
+
|
|
1116
|
+
adaptive_alias = bool(args.get("adaptive", False))
|
|
1117
|
+
adaptive_save = bool(args.get("adaptiveSave", False)) or adaptive_alias
|
|
1118
|
+
adaptive_relocate = bool(args.get("adaptiveRelocate", False)) or adaptive_alias
|
|
1119
|
+
adaptive = adaptive_save or adaptive_relocate
|
|
1120
|
+
if adaptive and query_type not in ("css", "xpath"):
|
|
1121
|
+
raise AdapterError("BAD_ARGS", "adaptive currently requires queryType css or xpath")
|
|
1122
|
+
|
|
1123
|
+
identifier = args.get("identifier")
|
|
1124
|
+
if identifier is not None and not isinstance(identifier, str):
|
|
1125
|
+
raise AdapterError("BAD_ARGS", "identifier must be a string or null")
|
|
1126
|
+
percentage = args.get("percentage")
|
|
1127
|
+
if percentage is not None and (
|
|
1128
|
+
not isinstance(percentage, int) or isinstance(percentage, bool) or not 1 <= percentage <= 100
|
|
1129
|
+
):
|
|
1130
|
+
raise AdapterError("BAD_ARGS", "percentage must be an integer between 1 and 100")
|
|
1131
|
+
similarity_threshold = args.get("similarityThreshold")
|
|
1132
|
+
if similarity_threshold is not None and (
|
|
1133
|
+
not isinstance(similarity_threshold, (int, float))
|
|
1134
|
+
or isinstance(similarity_threshold, bool)
|
|
1135
|
+
or not 0 <= similarity_threshold <= 1
|
|
1136
|
+
):
|
|
1137
|
+
raise AdapterError("BAD_ARGS", "similarityThreshold must be a number between 0 and 1")
|
|
1138
|
+
ignore_attributes = args.get("ignoreAttributes")
|
|
1139
|
+
if ignore_attributes is None:
|
|
1140
|
+
ignore_attributes = ("href", "src")
|
|
1141
|
+
elif not isinstance(ignore_attributes, (list, tuple)) or not all(
|
|
1142
|
+
isinstance(item, str) for item in ignore_attributes
|
|
1143
|
+
):
|
|
1144
|
+
raise AdapterError("BAD_ARGS", "ignoreAttributes must be an array of strings")
|
|
1145
|
+
|
|
1146
|
+
def query_nodes(target: Any, *, use_adaptive: bool) -> tuple[Any, str]:
|
|
1147
|
+
"""在给好的 Selector 上跑一次查询;``use_adaptive`` 决定带不带指纹参数。
|
|
1148
|
+
|
|
1149
|
+
降级路径要能拿**同一个**查询再跑一遍,所以查询本身收进闭包:自适应与普通两条路
|
|
1150
|
+
必须跑的是同一套 rules,否则「降级」会悄悄改变语义。
|
|
1151
|
+
"""
|
|
1152
|
+
if query_type in ("css", "xpath"):
|
|
1153
|
+
method = target.xpath if query_type == "xpath" else target.css
|
|
1154
|
+
selected = method(
|
|
1155
|
+
selector,
|
|
1156
|
+
identifier=identifier or "",
|
|
1157
|
+
adaptive=adaptive_relocate if use_adaptive else False,
|
|
1158
|
+
auto_save=adaptive_save if use_adaptive else False,
|
|
1159
|
+
percentage=percentage if percentage is not None else 40,
|
|
1160
|
+
)
|
|
1161
|
+
return selected, ""
|
|
1162
|
+
found, user_notice = extraction.query_nodes(
|
|
1163
|
+
target,
|
|
1164
|
+
selector,
|
|
1165
|
+
query_type,
|
|
1166
|
+
use_xpath=use_xpath,
|
|
1167
|
+
partial=bool(args.get("partial", False)),
|
|
1168
|
+
case_sensitive=bool(args.get("caseSensitive", False)),
|
|
1169
|
+
clean_match=bool(args.get("cleanMatch", True)),
|
|
1170
|
+
similarity_threshold=float(similarity_threshold) if similarity_threshold is not None else 0.2,
|
|
1171
|
+
ignore_attributes=ignore_attributes,
|
|
1172
|
+
match_text=bool(args.get("matchText", False)),
|
|
1173
|
+
)
|
|
1174
|
+
return found, user_notice
|
|
1175
|
+
|
|
1176
|
+
notice = ""
|
|
989
1177
|
if adaptive:
|
|
990
1178
|
# storage_args 必须把 url 一起带上:Scrapling 对「给了部分 storage_args」是整体
|
|
991
1179
|
# 替换而不是补齐,漏了 url 全部指纹都会落进 default 桶。url 为空时也显式传空串,
|
|
992
1180
|
# 存储层把它归入 default 桶(StorageSystemMixin 对空值有兜底)。
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1181
|
+
#
|
|
1182
|
+
# spec §7.2 / §12.2:存储故障**不使抽取失败** —— 降级为不带 adaptive 的普通
|
|
1183
|
+
# Selector 再抽一次,正文照常返回,notice 带 ADAPTIVE_STORAGE_FAILED 与原因。
|
|
1184
|
+
# sqlite 与 redis 两侧同解:指纹库坏了不该让模型连正文都拿不到。
|
|
1185
|
+
try:
|
|
1186
|
+
page = Selector(html, url=url or "", adaptive=True, **_adaptive_kwargs(args, url or ""))
|
|
1187
|
+
nodes, notice = query_nodes(page, use_adaptive=True)
|
|
1188
|
+
except AdapterError:
|
|
1189
|
+
raise
|
|
1190
|
+
except Exception as error: # noqa: BLE001 —— 存储后端的异常类型由它自己决定
|
|
1191
|
+
page = Selector(html, url=url or "")
|
|
1192
|
+
nodes, notice = query_nodes(page, use_adaptive=False)
|
|
1193
|
+
notice = f"ADAPTIVE_STORAGE_FAILED: {type(error).__name__}: {error}"
|
|
999
1194
|
else:
|
|
1000
|
-
page = Selector(html)
|
|
1195
|
+
page = Selector(html, url=url or "")
|
|
1196
|
+
nodes, notice = query_nodes(page, use_adaptive=False)
|
|
1001
1197
|
|
|
1002
|
-
# 命中成功时 auto_save 存指纹,命中失败且 adaptive 打开时按存过的指纹重定位 ——
|
|
1003
|
-
# 两个开关都必须在**调用**上再打开一次:Scrapling 的 adaptive 是构造器与调用两级
|
|
1004
|
-
# 开关,只开构造器的话,重定位会被静默跳过。
|
|
1005
|
-
use_xpath = bool(args.get("useXpath", False))
|
|
1006
|
-
if use_xpath:
|
|
1007
|
-
nodes = page.xpath(selector, adaptive=adaptive, auto_save=adaptive)
|
|
1008
|
-
else:
|
|
1009
|
-
nodes = page.css(selector, adaptive=adaptive, auto_save=adaptive)
|
|
1010
1198
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
1011
1199
|
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
|
|
1012
1200
|
include_attributes = bool(args.get("includeAttributes", False))
|
|
1201
|
+
include_html = bool(args.get("includeHtml", False))
|
|
1202
|
+
resolve_urls = bool(args.get("resolveUrls", False))
|
|
1203
|
+
fields = args.get("fields")
|
|
1204
|
+
|
|
1205
|
+
if fields is not None:
|
|
1206
|
+
if not isinstance(fields, dict):
|
|
1207
|
+
raise AdapterError("BAD_ARGS", "fields must be an object or null")
|
|
1208
|
+
try:
|
|
1209
|
+
rows, fields_truncated = extraction.collect_fields(
|
|
1210
|
+
list(nodes)[:limit],
|
|
1211
|
+
fields,
|
|
1212
|
+
page=page,
|
|
1213
|
+
max_content_chars=budget,
|
|
1214
|
+
resolve_urls=resolve_urls,
|
|
1215
|
+
)
|
|
1216
|
+
except ValueError as error:
|
|
1217
|
+
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1218
|
+
return {
|
|
1219
|
+
"count": len(nodes),
|
|
1220
|
+
"truncated": fields_truncated or len(nodes) > limit,
|
|
1221
|
+
"rows": _jsonable(rows),
|
|
1222
|
+
"notice": notice,
|
|
1223
|
+
}
|
|
1013
1224
|
|
|
1014
1225
|
matches: list[dict[str, Any]] = []
|
|
1015
1226
|
spent = 0
|
|
@@ -1017,18 +1228,24 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1017
1228
|
for node in nodes:
|
|
1018
1229
|
if len(matches) >= limit:
|
|
1019
1230
|
break
|
|
1020
|
-
item
|
|
1231
|
+
item = extraction.serialize_match(
|
|
1232
|
+
node,
|
|
1233
|
+
page=page,
|
|
1234
|
+
attribute=attribute,
|
|
1235
|
+
include_attributes=include_attributes,
|
|
1236
|
+
include_html=include_html,
|
|
1237
|
+
resolve_urls=resolve_urls,
|
|
1238
|
+
)
|
|
1021
1239
|
field = "value" if attribute else "text"
|
|
1022
|
-
|
|
1023
|
-
if include_attributes:
|
|
1024
|
-
item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
|
|
1240
|
+
value = str(item.get(field, ""))
|
|
1025
1241
|
# 先按剩余额度截再计入已花:一条超长正文不该把整份预算吃光,也不该在预算只剩
|
|
1026
1242
|
# 一位时还能整条通过。
|
|
1027
1243
|
room = max(0, budget - spent)
|
|
1028
|
-
if len(
|
|
1029
|
-
|
|
1244
|
+
if len(value) > room:
|
|
1245
|
+
value = value[:room]
|
|
1030
1246
|
clipped = True
|
|
1031
|
-
|
|
1247
|
+
item[field] = value
|
|
1248
|
+
spent += len(value)
|
|
1032
1249
|
matches.append(item)
|
|
1033
1250
|
if spent >= budget:
|
|
1034
1251
|
clipped = True
|
|
@@ -1037,6 +1254,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1037
1254
|
"count": len(nodes),
|
|
1038
1255
|
"truncated": clipped or len(nodes) > len(matches),
|
|
1039
1256
|
"matches": _jsonable(matches),
|
|
1257
|
+
"notice": notice,
|
|
1040
1258
|
}
|
|
1041
1259
|
|
|
1042
1260
|
|
|
@@ -1087,6 +1305,21 @@ def _probe_browser(module_name: str) -> bool:
|
|
|
1087
1305
|
return True
|
|
1088
1306
|
|
|
1089
1307
|
|
|
1308
|
+
def _websocket_guard_capability() -> bool:
|
|
1309
|
+
"""不启浏览器就判断 WebSocket 握手拦不拦得住。
|
|
1310
|
+
|
|
1311
|
+
``route_web_socket`` 挂在 Page 类上而不是实例上,所以握手那一刻就能答,不必等第一
|
|
1312
|
+
个页面建起来 —— 而 README 承诺的正是「能力报告里如实标出覆盖面」。
|
|
1313
|
+
|
|
1314
|
+
:returns: 当前安装的 patchright 是否支持拦截 WebSocket 握手(缺包算不支持)
|
|
1315
|
+
"""
|
|
1316
|
+
try:
|
|
1317
|
+
from patchright.sync_api import Page
|
|
1318
|
+
except ImportError:
|
|
1319
|
+
return False
|
|
1320
|
+
return guard.websocket_guard_supported(Page)
|
|
1321
|
+
|
|
1322
|
+
|
|
1090
1323
|
def capabilities() -> dict[str, Any]:
|
|
1091
1324
|
"""报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
|
|
1092
1325
|
report: dict[str, Any] = {
|
|
@@ -1104,20 +1337,46 @@ def capabilities() -> dict[str, Any]:
|
|
|
1104
1337
|
# 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
|
|
1105
1338
|
# 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的口径已经没有第二个引擎可标。
|
|
1106
1339
|
report["browser"] = _probe_browser("patchright.sync_api")
|
|
1340
|
+
# 浏览器守卫覆盖面的那一半(WebSocket 握手)在这里报出:拦不住时 install 只会往 stderr
|
|
1341
|
+
# 记一行,而那要等第一个页面建起来才看得见 —— 排障的人得在装载阶段就知道。
|
|
1342
|
+
report["websocketGuard"] = _websocket_guard_capability()
|
|
1107
1343
|
# 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
|
|
1108
1344
|
# server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
|
|
1109
1345
|
report["proxy"] = guard.proxy_settings()
|
|
1110
1346
|
return report
|
|
1111
1347
|
|
|
1112
1348
|
|
|
1349
|
+
def _wrap_extraction(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1350
|
+
"""把 extraction 的 ValueError 归成协议里的 BAD_ARGS。"""
|
|
1351
|
+
try:
|
|
1352
|
+
return fn(args)
|
|
1353
|
+
except ValueError as error:
|
|
1354
|
+
raise AdapterError("BAD_ARGS", str(error)) from error
|
|
1355
|
+
|
|
1356
|
+
|
|
1357
|
+
def _wrap_search(fn: Callable[[dict[str, Any]], dict[str, Any]], args: dict[str, Any]) -> dict[str, Any]:
|
|
1358
|
+
"""把 SearchError 的码原样转成协议错误。"""
|
|
1359
|
+
try:
|
|
1360
|
+
return fn(args)
|
|
1361
|
+
except search.SearchError as error:
|
|
1362
|
+
raise AdapterError(error.code, str(error)) from error
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
def search_discover(args: dict[str, Any]) -> dict[str, Any]:
|
|
1366
|
+
"""协议入口:检索发现。"""
|
|
1367
|
+
return _wrap_search(search.discover, args)
|
|
1368
|
+
|
|
1369
|
+
|
|
1113
1370
|
METHODS = {
|
|
1114
1371
|
"ping": lambda _args: {"pong": True},
|
|
1115
1372
|
"capabilities": lambda _args: capabilities(),
|
|
1116
1373
|
"fetch": fetch,
|
|
1117
1374
|
"render": render,
|
|
1118
1375
|
"capture": capture,
|
|
1119
|
-
"extract": extract,
|
|
1120
1376
|
"select": select,
|
|
1377
|
+
"locate": lambda args: _wrap_extraction(extraction.locate, args),
|
|
1378
|
+
"links": lambda args: _wrap_extraction(extraction.links, args),
|
|
1379
|
+
"search.discover": search_discover,
|
|
1121
1380
|
}
|
|
1122
1381
|
|
|
1123
1382
|
|
|
@@ -1161,6 +1420,11 @@ MAX_SESSIONS = 8
|
|
|
1161
1420
|
# 其中最多几个可以是吃内存的浏览器会话。static 只是连接池,便宜得多。
|
|
1162
1421
|
MAX_BROWSER_SESSIONS = 3
|
|
1163
1422
|
|
|
1423
|
+
# 等属主线程回结果的预算。这是**兜底**,不是抓取超时:单次调用的超时由它自己的
|
|
1424
|
+
# timeoutSeconds 管(浏览器导航可能合法地跑上几分钟),这里只负责把「线程已经不在了」
|
|
1425
|
+
# 从「调用很慢」里分出来。取 10 分钟是为了让最长的合法抓取仍先于它触发。
|
|
1426
|
+
_WORKER_RESULT_TIMEOUT_SECONDS = 600.0
|
|
1427
|
+
|
|
1164
1428
|
|
|
1165
1429
|
class _SessionWorker:
|
|
1166
1430
|
"""一个会话的**专属执行线程**:这份会话上的全部远端调用都在它上面排队执行。
|
|
@@ -1177,6 +1441,10 @@ class _SessionWorker:
|
|
|
1177
1441
|
def __init__(self) -> None:
|
|
1178
1442
|
self._jobs: "queue.SimpleQueue[tuple[Callable[[], Any], concurrent.futures.Future[Any]] | None]"
|
|
1179
1443
|
self._jobs = queue.SimpleQueue()
|
|
1444
|
+
# stop() 之后 _loop 已经取走哨兵并返回:此后投进来的任务永远排在一个没人消费的
|
|
1445
|
+
# 队列里,而 run() 的 done.result() 没有超时 —— 调用方会永久阻塞。用这个标记把
|
|
1446
|
+
# 「已停止」变成立刻可见的错误,而不是一次等不到回音的等待。
|
|
1447
|
+
self._closed = threading.Event()
|
|
1180
1448
|
self._thread = threading.Thread(target=self._loop, daemon=True, name="session-worker")
|
|
1181
1449
|
self._thread.start()
|
|
1182
1450
|
|
|
@@ -1195,22 +1463,37 @@ class _SessionWorker:
|
|
|
1195
1463
|
except BaseException as error: # noqa: BLE001 —— 任务异常必须回到调用方线程
|
|
1196
1464
|
done.set_exception(error)
|
|
1197
1465
|
|
|
1198
|
-
def run(self, fn: Callable[[], Any]) -> Any: #
|
|
1466
|
+
def run(self, fn: Callable[[], Any]) -> Any: # 会话调用的返回形态由引擎定
|
|
1199
1467
|
"""把 fn 投递到属主线程执行,并阻塞调用线程直到它结束。
|
|
1200
1468
|
|
|
1201
1469
|
:param fn: 要在属主线程上执行的调用
|
|
1202
1470
|
:returns: fn 的返回值
|
|
1471
|
+
:raises AdapterError: 这条线程已经停止,投进去也没有人会执行
|
|
1203
1472
|
:raises BaseException: fn 抛什么这里就抛什么
|
|
1204
1473
|
"""
|
|
1474
|
+
# 与 stop() 之间没有锁:检查通过之后 stop() 仍可能抢先取走哨兵。那个窗口里
|
|
1475
|
+
# put 进队列的任务确实没人消费,所以下面的 result 必须带超时兜底。
|
|
1476
|
+
if self._closed.is_set():
|
|
1477
|
+
raise AdapterError("NO_SUCH_SESSION", "session has already been closed")
|
|
1205
1478
|
done: concurrent.futures.Future[Any] = concurrent.futures.Future()
|
|
1206
1479
|
self._jobs.put((fn, done))
|
|
1207
|
-
|
|
1480
|
+
try:
|
|
1481
|
+
return done.result(timeout=_WORKER_RESULT_TIMEOUT_SECONDS)
|
|
1482
|
+
except concurrent.futures.TimeoutError:
|
|
1483
|
+
# fn 里真实的长调用(浏览器导航、大页面抓取)不该走到这里:那个预算由它自己的
|
|
1484
|
+
# 超时管。到这里说明这条线程已经不在了,继续等只会把调用方一起挂死。
|
|
1485
|
+
raise AdapterError("SESSION_CLOSED", "session worker did not answer; the session is gone") from None
|
|
1208
1486
|
|
|
1209
1487
|
def stop(self) -> None:
|
|
1210
1488
|
"""发哨兵收线程。队列里的任务会先跑完,所以 close 之后 stop 是安全的。"""
|
|
1489
|
+
self._closed.set()
|
|
1211
1490
|
self._jobs.put(None)
|
|
1212
1491
|
self._thread.join(timeout=5.0)
|
|
1213
1492
|
|
|
1493
|
+
def alive(self) -> bool:
|
|
1494
|
+
"""属主线程是否还在跑(T10 的 ``alive`` 判据:只读,不改动任何状态)。"""
|
|
1495
|
+
return not self._closed.is_set() and self._thread.is_alive()
|
|
1496
|
+
|
|
1214
1497
|
|
|
1215
1498
|
def _new_session_id() -> str:
|
|
1216
1499
|
"""生成一个短的会话 id。
|
|
@@ -1360,6 +1643,9 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1360
1643
|
"closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
|
|
1361
1644
|
"type": kind,
|
|
1362
1645
|
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
1646
|
+
# T10 的非敏感设置摘要:在开场时把生效值记下来,session.list 不必回头去
|
|
1647
|
+
# 猜(凭据面永远不进这份摘要)。
|
|
1648
|
+
"settings": _session_settings(kind, args),
|
|
1363
1649
|
# 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
|
|
1364
1650
|
"lock": entry_lock,
|
|
1365
1651
|
# browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
|
|
@@ -1369,9 +1655,15 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1369
1655
|
if abandoned:
|
|
1370
1656
|
# 构造期间已经被要求关闭(sidecar 关机走的就是 close_all_sessions):这一份刚建好的
|
|
1371
1657
|
# 会话绝不能登记 —— 登记了就没有任何人会再去关它,浏览器进程会活过 sidecar 自己。
|
|
1372
|
-
|
|
1658
|
+
abandoned_entry = {"closer": closer, "type": kind, "lock": entry_lock}
|
|
1373
1659
|
if worker is not None:
|
|
1660
|
+
# 浏览器会话的 close 必须在属主线程上跑:Playwright 的同步 API 与创建它的线程
|
|
1661
|
+
# 绑定,跨线程调用抛 greenlet 错误,而 _release_entry 会 suppress 掉它 ——
|
|
1662
|
+
# 随后 stop() 又把属主线程收掉,这个 Chromium 就再没有任何线程能关。
|
|
1663
|
+
worker.run(lambda: _release_entry(abandoned_entry))
|
|
1374
1664
|
worker.stop()
|
|
1665
|
+
else:
|
|
1666
|
+
_release_entry(abandoned_entry)
|
|
1375
1667
|
return {
|
|
1376
1668
|
"sessionId": session_id,
|
|
1377
1669
|
"sessionType": kind,
|
|
@@ -1411,6 +1703,9 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1411
1703
|
session = entry["session"]
|
|
1412
1704
|
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1413
1705
|
url = _url(args)
|
|
1706
|
+
# 这两枚在载荷阶段才用到;提前读一次,让协议对表看到它们不是死键。
|
|
1707
|
+
strip_inline_images = _strip_inline_images(args)
|
|
1708
|
+
include_metadata = bool(args.get("includeMetadata", False))
|
|
1414
1709
|
|
|
1415
1710
|
# 一份会话同一时刻只服务一个请求:static 靠 entry 锁,浏览器会话靠属主线程天然串行。
|
|
1416
1711
|
# 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
|
|
@@ -1424,7 +1719,19 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1424
1719
|
allowed, reason = guard.url_allowed(url)
|
|
1425
1720
|
if not allowed:
|
|
1426
1721
|
raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
|
|
1427
|
-
|
|
1722
|
+
# form/json 是 POST 的请求体:没有写方法表态时按写意图拒绝,而不是把
|
|
1723
|
+
# 它们塞进一次 GET(那会变成「发出去但语义错了」,比报错更难查)。
|
|
1724
|
+
write_body = args.get("form") is not None or args.get("json") is not None
|
|
1725
|
+
static_method = "POST" if write_body else "GET"
|
|
1726
|
+
if static_method != "GET" and not guard.ALLOW_WRITE_METHODS:
|
|
1727
|
+
raise AdapterError(
|
|
1728
|
+
"WRITE_DISABLED",
|
|
1729
|
+
"form/json change the request into POST; the deployment must set "
|
|
1730
|
+
f"allowWriteMethods (env {guard.ALLOW_WRITE_METHODS_ENV}) to allow it",
|
|
1731
|
+
)
|
|
1732
|
+
static_params = _static_params(args, url)
|
|
1733
|
+
static_params.update(_static_request_payload(args, static_method))
|
|
1734
|
+
response = getattr(session, static_method.lower())(url, **static_params)
|
|
1428
1735
|
else:
|
|
1429
1736
|
# 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
|
|
1430
1737
|
# 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
|
|
@@ -1446,7 +1753,14 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1446
1753
|
#
|
|
1447
1754
|
# 空的没给(`{}` / `[]` / null)不算写意图:模型「不带任何请求头」时传的就是空表,
|
|
1448
1755
|
# 为它报一条错等于把一个无害的调用说成非法。
|
|
1449
|
-
for key, hint in (
|
|
1756
|
+
for key, hint in (
|
|
1757
|
+
("headers", "extraHeaders"),
|
|
1758
|
+
("retries", "scrapling_session_open"),
|
|
1759
|
+
("cookies", "scrapling_session_open"),
|
|
1760
|
+
("params", "a static session"),
|
|
1761
|
+
("form", "a static session"),
|
|
1762
|
+
("json", "a static session"),
|
|
1763
|
+
):
|
|
1450
1764
|
if args.get(key) not in (None, {}, []):
|
|
1451
1765
|
raise AdapterError(
|
|
1452
1766
|
"BAD_ARGS",
|
|
@@ -1460,7 +1774,7 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1460
1774
|
response = worker.run(lambda: session.fetch(url, **params))
|
|
1461
1775
|
except AdapterError:
|
|
1462
1776
|
raise
|
|
1463
|
-
except Exception as error:
|
|
1777
|
+
except Exception as error:
|
|
1464
1778
|
raise AdapterError("FETCH_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1465
1779
|
|
|
1466
1780
|
payload = to_payload(
|
|
@@ -1469,30 +1783,192 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1469
1783
|
css_selector=css_selector,
|
|
1470
1784
|
main_content_only=main_content_only,
|
|
1471
1785
|
max_content_chars=limit,
|
|
1472
|
-
strip_inline_images=
|
|
1786
|
+
strip_inline_images=strip_inline_images,
|
|
1787
|
+
include_metadata=include_metadata,
|
|
1473
1788
|
)
|
|
1474
1789
|
payload["sessionId"] = args.get("sessionId")
|
|
1475
1790
|
return payload
|
|
1476
1791
|
|
|
1477
1792
|
|
|
1793
|
+
def session_read(args: dict[str, Any]) -> dict[str, Any]:
|
|
1794
|
+
"""读浏览器会话当前页的正文,不再发一次请求。"""
|
|
1795
|
+
entry = _get_session(args.get("sessionId"))
|
|
1796
|
+
if entry["type"] == "static":
|
|
1797
|
+
raise AdapterError("BAD_ARGS", "only browser sessions keep a current page")
|
|
1798
|
+
extraction_type, css_selector, main_content_only, limit = _extraction(args)
|
|
1799
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1800
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1801
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1802
|
+
from session_page import read_current_page
|
|
1803
|
+
|
|
1804
|
+
return worker.run(
|
|
1805
|
+
lambda: read_current_page(
|
|
1806
|
+
entry["session"],
|
|
1807
|
+
extraction_type=extraction_type,
|
|
1808
|
+
css_selector=css_selector,
|
|
1809
|
+
main_content_only=main_content_only,
|
|
1810
|
+
max_content_chars=limit,
|
|
1811
|
+
include_metadata=bool(args.get("includeMetadata", False)),
|
|
1812
|
+
strip_inline_images=_strip_inline_images(args),
|
|
1813
|
+
)
|
|
1814
|
+
)
|
|
1815
|
+
|
|
1816
|
+
|
|
1817
|
+
def session_act(args: dict[str, Any]) -> dict[str, Any]:
|
|
1818
|
+
"""在一个浏览器会话的当前页上执行结构化动作。"""
|
|
1819
|
+
if not guard.ALLOW_BROWSER_ACTIONS:
|
|
1820
|
+
raise AdapterError(
|
|
1821
|
+
"ACTION_DISABLED",
|
|
1822
|
+
f"browser actions are disabled; the deployment must set {guard.ALLOW_BROWSER_ACTIONS_ENV}",
|
|
1823
|
+
)
|
|
1824
|
+
entry = _get_session(args.get("sessionId"))
|
|
1825
|
+
if entry["type"] == "static":
|
|
1826
|
+
raise AdapterError("BAD_ARGS", "only browser sessions support actions")
|
|
1827
|
+
max_actions = _positive_int(args.get("maxActions"), "maxActions", 20)
|
|
1828
|
+
if max_actions > 50:
|
|
1829
|
+
raise AdapterError("BAD_ARGS", "maxActions cannot exceed 50")
|
|
1830
|
+
timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
|
|
1831
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1832
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1833
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1834
|
+
from session_page import run_actions
|
|
1835
|
+
|
|
1836
|
+
return worker.run(
|
|
1837
|
+
lambda: run_actions(
|
|
1838
|
+
entry["session"],
|
|
1839
|
+
actions=args.get("actions"),
|
|
1840
|
+
slowly=args.get("slowly") is True,
|
|
1841
|
+
max_actions=max_actions,
|
|
1842
|
+
timeout_ms=timeout_ms,
|
|
1843
|
+
)
|
|
1844
|
+
)
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def download(args: dict[str, Any]) -> dict[str, Any]:
|
|
1848
|
+
"""受门禁保护的下载入口。"""
|
|
1849
|
+
return media.download(args)
|
|
1850
|
+
|
|
1851
|
+
|
|
1852
|
+
def screenshot(args: dict[str, Any]) -> dict[str, Any]:
|
|
1853
|
+
"""截当前会话页;不会新建浏览器。"""
|
|
1854
|
+
entry = _get_session(args.get("sessionId"))
|
|
1855
|
+
if entry["type"] == "static":
|
|
1856
|
+
raise AdapterError("BAD_ARGS", "only browser sessions can take screenshots")
|
|
1857
|
+
image_type = args.get("imageType", "png")
|
|
1858
|
+
if not isinstance(image_type, str):
|
|
1859
|
+
raise AdapterError("BAD_ARGS", "imageType must be a string")
|
|
1860
|
+
selector = args.get("selector")
|
|
1861
|
+
if selector is not None and not isinstance(selector, str):
|
|
1862
|
+
raise AdapterError("BAD_ARGS", "selector must be a string or null")
|
|
1863
|
+
quality = args.get("quality")
|
|
1864
|
+
timeout_ms = _positive_int(args.get("timeoutMs"), "timeoutMs", DEFAULT_TIMEOUT_MS)
|
|
1865
|
+
worker: _SessionWorker | None = entry["worker"]
|
|
1866
|
+
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1867
|
+
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1868
|
+
return worker.run(
|
|
1869
|
+
lambda: media.screenshot(
|
|
1870
|
+
entry["session"],
|
|
1871
|
+
image_type=image_type,
|
|
1872
|
+
full_page=args.get("fullPage") is True,
|
|
1873
|
+
quality=quality,
|
|
1874
|
+
selector=selector,
|
|
1875
|
+
timeout_ms=timeout_ms,
|
|
1876
|
+
)
|
|
1877
|
+
)
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def _session_settings(kind: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
1881
|
+
"""会话的非敏感设置摘要(T10)。
|
|
1882
|
+
|
|
1883
|
+
只收「这次会话是怎么配的」的开关,绝不包含 cookies、代理凭据或任何 key —— 这份
|
|
1884
|
+
摘要会被模型读到。静态会话没有浏览器那一组开关,逐项给 null。
|
|
1885
|
+
|
|
1886
|
+
:param kind: 会话类型
|
|
1887
|
+
:param args: session.open 的协议参数
|
|
1888
|
+
:returns: 可 JSON 序列化的摘要
|
|
1889
|
+
"""
|
|
1890
|
+
deployment = args.get("deployment")
|
|
1891
|
+
knobs = deployment if isinstance(deployment, dict) else {}
|
|
1892
|
+
browser = kind != "static"
|
|
1893
|
+
headless = args.get("headless", True)
|
|
1894
|
+
locale = args.get("locale")
|
|
1895
|
+
timezone_id = args.get("timezoneId")
|
|
1896
|
+
recorded = browser and (args.get("recordNetwork") is True or _knob_value(bool, knobs.get("recordRequests")) is True)
|
|
1897
|
+
return {
|
|
1898
|
+
"type": kind,
|
|
1899
|
+
"headless": bool(headless) if browser else None,
|
|
1900
|
+
"recordNetwork": recorded,
|
|
1901
|
+
"maxRecordedRequests": _knob_value(int, knobs.get("maxRecordedRequests")),
|
|
1902
|
+
"locale": locale if isinstance(locale, str) and locale else None,
|
|
1903
|
+
"timezone": timezone_id if isinstance(timezone_id, str) and timezone_id else None,
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def _session_alive(entry: dict[str, Any]) -> bool:
|
|
1908
|
+
"""会话是否还能用:构造中的占位不算,浏览器会话还要属主线程活着。
|
|
1909
|
+
|
|
1910
|
+
:param entry: 登记条目
|
|
1911
|
+
:returns: 是否可用
|
|
1912
|
+
"""
|
|
1913
|
+
if entry.get("pending") is True:
|
|
1914
|
+
return False
|
|
1915
|
+
worker = entry.get("worker")
|
|
1916
|
+
if worker is not None:
|
|
1917
|
+
return worker.alive() is True
|
|
1918
|
+
return entry.get("session") is not None
|
|
1919
|
+
|
|
1920
|
+
|
|
1921
|
+
def _pool_stats(entry: dict[str, Any]) -> dict[str, int] | None:
|
|
1922
|
+
"""浏览器会话的页池统计;没有这条能力或取不到时给 None(绝不抛)。
|
|
1923
|
+
|
|
1924
|
+
T10 的 ``poolStats`` 是可选字段:一只已经跑完开始收尾的会话也可能在取统计的一瞬
|
|
1925
|
+
出错,那不该把整个 session.list 变成一次失败。
|
|
1926
|
+
|
|
1927
|
+
:param entry: 登记条目
|
|
1928
|
+
:returns: 页池统计,或 None
|
|
1929
|
+
"""
|
|
1930
|
+
if entry.get("type") == "static":
|
|
1931
|
+
return None
|
|
1932
|
+
session = entry.get("session")
|
|
1933
|
+
getter = getattr(session, "get_pool_stats", None)
|
|
1934
|
+
if not callable(getter):
|
|
1935
|
+
return None
|
|
1936
|
+
try:
|
|
1937
|
+
stats = getter()
|
|
1938
|
+
except Exception: # noqa: BLE001 —— T10:统计拿不到时省略,不许让 list 整体失败
|
|
1939
|
+
return None
|
|
1940
|
+
if not isinstance(stats, dict):
|
|
1941
|
+
return None
|
|
1942
|
+
return {str(key): value for key, value in stats.items() if isinstance(value, int) and not isinstance(value, bool)}
|
|
1943
|
+
|
|
1944
|
+
|
|
1478
1945
|
def session_list(_args: dict[str, Any]) -> dict[str, Any]:
|
|
1479
1946
|
"""列出当前所有会话(不含任何凭据)。
|
|
1480
1947
|
|
|
1948
|
+
每行除 id / type / createdAt 之外还带 ``alive``、``settings``(非敏感设置摘要)与
|
|
1949
|
+
``poolStats``(浏览器会话取得到页池统计时才给;取不到就省略,绝不因此让 list 失败)。
|
|
1950
|
+
|
|
1481
1951
|
:param _args: 协议参数,本方法不用
|
|
1482
1952
|
:returns: 会话列表
|
|
1483
1953
|
"""
|
|
1484
1954
|
# 字典遍历期间被别的线程插入/删除会抛 RuntimeError,而那正是 bridge 多 worker 下的
|
|
1485
1955
|
# 常态。进锁里把清单复制出来,遍历就与并发改写无关。
|
|
1486
1956
|
with _SESSION_LOCK:
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1957
|
+
entries = list(_SESSIONS.items())
|
|
1958
|
+
rows: list[dict[str, Any]] = []
|
|
1959
|
+
for session_id, entry in entries:
|
|
1960
|
+
row: dict[str, Any] = {
|
|
1961
|
+
"sessionId": session_id,
|
|
1962
|
+
"sessionType": entry["type"],
|
|
1963
|
+
# 构造中的条目还没有创建时间;报空串而不是 KeyError。
|
|
1964
|
+
"createdAt": entry.get("created_at", ""),
|
|
1965
|
+
"alive": _session_alive(entry),
|
|
1966
|
+
"settings": entry.get("settings") or _session_settings(str(entry.get("type", "")), {}),
|
|
1967
|
+
}
|
|
1968
|
+
stats = _pool_stats(entry)
|
|
1969
|
+
if stats is not None:
|
|
1970
|
+
row["poolStats"] = stats
|
|
1971
|
+
rows.append(row)
|
|
1496
1972
|
return {"sessions": rows}
|
|
1497
1973
|
|
|
1498
1974
|
|
|
@@ -1514,13 +1990,17 @@ def _close_entry(session_id: Any) -> None:
|
|
|
1514
1990
|
"""
|
|
1515
1991
|
with _SESSION_LOCK:
|
|
1516
1992
|
entry = _SESSIONS.pop(session_id, None)
|
|
1993
|
+
if entry is not None and entry.get("pending") is True:
|
|
1994
|
+
# 墓碑必须与 pop 在同一个临界区:session_open 是在 _SESSION_LOCK 里读它的。
|
|
1995
|
+
# 写在锁外会留下这个时序 —— 这里已 pop 并释放锁,构造方接着在锁内读到 False
|
|
1996
|
+
# 并把建好的会话登记回 _SESSIONS,之后才轮到写 True,那条会话就没人关了。
|
|
1997
|
+
entry["closed_while_pending"] = True
|
|
1517
1998
|
if entry is None:
|
|
1518
1999
|
return
|
|
1519
2000
|
if entry.get("pending") is True:
|
|
1520
2001
|
# 还没构造完:构造方自己会在成功时覆盖这一条,或在失败时把它摘掉。这里不能碰
|
|
1521
|
-
# closer ——
|
|
2002
|
+
# closer —— 它还不存在。但墓碑已经留下:构造方一会儿会把建好的会话登记回来,
|
|
1522
2003
|
# 那一步要看见这次关闭,否则刚建好的浏览器没有任何人会再去关它。
|
|
1523
|
-
entry["closed_while_pending"] = True
|
|
1524
2004
|
return
|
|
1525
2005
|
worker: _SessionWorker | None = entry.get("worker")
|
|
1526
2006
|
if worker is not None:
|
|
@@ -1566,7 +2046,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1566
2046
|
entry = _get_session(session_id)
|
|
1567
2047
|
if entry["type"] == "static":
|
|
1568
2048
|
raise AdapterError("BAD_ARGS", "static sessions keep no network history")
|
|
1569
|
-
|
|
2049
|
+
query = _network_read(args)
|
|
1570
2050
|
recorder = getattr(entry["session"], "network", None)
|
|
1571
2051
|
if recorder is None or not getattr(recorder, "enabled", False):
|
|
1572
2052
|
raise AdapterError(
|
|
@@ -1577,15 +2057,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
1577
2057
|
worker: _SessionWorker | None = entry["worker"]
|
|
1578
2058
|
if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
|
|
1579
2059
|
raise AdapterError("NO_SUCH_SESSION", "session has no owner thread")
|
|
1580
|
-
matches = worker.run(
|
|
1581
|
-
lambda: _network_summary(
|
|
1582
|
-
recorder,
|
|
1583
|
-
pattern=pattern,
|
|
1584
|
-
limit=entries,
|
|
1585
|
-
include_body=include_body,
|
|
1586
|
-
max_body_chars=body_chars,
|
|
1587
|
-
)
|
|
1588
|
-
)
|
|
2060
|
+
matches = worker.run(lambda: _network_summary(recorder, query=query))
|
|
1589
2061
|
return {"sessionId": session_id, "count": len(matches), "matches": matches}
|
|
1590
2062
|
|
|
1591
2063
|
|
|
@@ -1641,9 +2113,13 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
|
|
|
1641
2113
|
try:
|
|
1642
2114
|
if saving:
|
|
1643
2115
|
worker.run(lambda: session.save_state(target))
|
|
2116
|
+
# spec §11.6:登录态文件是凭据面(cookie / localStorage / IndexedDB),落盘后
|
|
2117
|
+
# 收到 0600。Windows 上 chmod 只动只读位,失败也不该让存取整体失败。
|
|
2118
|
+
with contextlib.suppress(OSError):
|
|
2119
|
+
Path(target).chmod(0o600)
|
|
1644
2120
|
else:
|
|
1645
2121
|
worker.run(lambda: session.load_state(target))
|
|
1646
|
-
except Exception as error: #
|
|
2122
|
+
except Exception as error: # 上游的文件/JSON 错误一律翻成可路由的码
|
|
1647
2123
|
raise AdapterError("STATE_FAILED", f"{type(error).__name__}: {error}") from error
|
|
1648
2124
|
return {"sessionId": session_id, "path": target, "saved": saving}
|
|
1649
2125
|
|
|
@@ -1685,6 +2161,10 @@ METHODS.update(
|
|
|
1685
2161
|
"session.list": session_list,
|
|
1686
2162
|
"session.close": session_close,
|
|
1687
2163
|
"session.network": session_network,
|
|
2164
|
+
"session.read": session_read,
|
|
2165
|
+
"session.act": session_act,
|
|
2166
|
+
"download": download,
|
|
2167
|
+
"screenshot": screenshot,
|
|
1688
2168
|
"session.state_save": session_state_save,
|
|
1689
2169
|
"session.state_load": session_state_load,
|
|
1690
2170
|
}
|