@jayyuen66/dsh-scrapling 0.1.2 → 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/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
- # 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要是**给模型看的**——它进会话
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
- 三处各藏一类凭据:查询串与片段的查询部分按**参数名**判(真实站点把 access token、
205
- 会话 id、签名放在那里),authority 里的 ``user:pass@`` 整段丢掉(代理与 Basic 认证
206
- 的接口都爱这么写)。值的部分一律换成固定占位符:定位接口靠的是路径与参数名,不是
207
- 那个 token。
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
164
  network: Any, # 上游的 NetworkRecorder
230
165
  *,
231
- pattern: str | None,
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
- records = network.search(url_pattern=pattern, limit=limit, include_static=False)
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
- "method": str(meta.get("method") or item.request_headers.get("method") or "GET"),
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, max_body_chars)
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
- except Exception: # noqa: BLE001 —— 单条摘要失败不该拖垮整次读取
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 == "html":
430
- page = _sanitized_page(response, main_content_only=main_content_only)
431
- _strip_active_content(page)
432
- content = "\n".join(element.html_content for element in _scoped_pages(page, css_selector))
433
- elif extraction_type == "text":
434
- page = _sanitized_page(response, main_content_only=main_content_only)
435
- content = "\n".join(
436
- element.get_all_text(
437
- strip=True,
438
- ignore_tags=("script", "style", "noscript", "svg", "iframe"),
439
- )
440
- for element in _scoped_pages(page, css_selector)
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
- content = response.markdown(css_selector=css_selector, main_content_only=main_content_only)
444
-
445
- text = str(content)
446
- # 先剥再封顶:被剥掉的那几十 KB 不该占 max_content_chars 的额度,否则一页内联图就能把
447
- # 真正文挤出预算 —— 顺序反了等于白剥。
448
- if strip_inline_images:
449
- text = drop_data_uris(text, html=extraction_type == "html")
450
- clipped, truncated = clip(text, max_content_chars)
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": len(getattr(response, "history", ()) or ()),
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
- if method != "GET":
541
- body = args.get("body")
542
- if isinstance(body, str):
543
- params["data"] = body
544
- elif body is not None:
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
 
@@ -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
- "blocked_domains": None,
721
- "disable_resources": False,
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
- def _network_read(args: dict[str, Any]) -> tuple[str | None, int, bool, int]:
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: (URL 过滤正则, 条数上限, 是否回传正文, 单条正文预算)
933
+ :returns: 归一后的查询参数
816
934
  """
817
- return (
818
- _url_pattern(args),
819
- _positive_int(args.get("networkLimit"), "networkLimit", DEFAULT_NETWORK_ENTRIES),
820
- bool(args.get("includeBody", False)),
821
- _positive_int(args.get("maxBodyChars"), "maxBodyChars", DEFAULT_NETWORK_BODY_CHARS),
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
- pattern: str | None,
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,10 +975,7 @@ def _capture_once(
838
975
 
839
976
  :param args: 协议参数
840
977
  :param url: 要抓的地址
841
- :param pattern: URL 过滤正则
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
@@ -864,13 +998,7 @@ def _capture_once(
864
998
  try:
865
999
  session.start()
866
1000
  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
- )
1001
+ records = _network_summary(session.network, query=query)
874
1002
  finally:
875
1003
  # 这条会话不进注册表,所以没有别人会替它收尸 —— 成败都要在这里关掉。
876
1004
  with contextlib.suppress(Exception):
@@ -893,22 +1021,13 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
893
1021
  _require(StealthyFetcher)
894
1022
  url = _url(args)
895
1023
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
896
- pattern, entries, include_body, body_chars = _network_read(args)
1024
+ query = _network_read(args)
897
1025
 
898
1026
  # 整条链路投到一条专属线程上:patchright 的同步 API 与创建它的线程绑定(greenlet),
899
1027
  # 而 bridge 的 worker 线程是「谁抢到帧谁处理」,所以这里建一条自己的、用完就收。
900
1028
  worker = _SessionWorker()
901
1029
  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
- )
1030
+ response, records = worker.run(lambda: _capture_once(args, url=url, query=query))
912
1031
  finally:
913
1032
  worker.stop()
914
1033
 
@@ -919,13 +1038,18 @@ def capture(args: dict[str, Any]) -> dict[str, Any]:
919
1038
  main_content_only=main_content_only,
920
1039
  max_content_chars=limit,
921
1040
  strip_inline_images=_strip_inline_images(args),
1041
+ include_metadata=bool(args.get("includeMetadata", False)),
922
1042
  )
923
1043
  payload["xhr"] = records
924
1044
  return payload
925
1045
 
926
1046
 
927
1047
  def _fake_response(html: str, url: str, status: int) -> Any:
928
- """造一个不带网络的 ``Response``,给离线抽取用。"""
1048
+ """造一个不带网络的 ``Response``,让已有 HTML 走与抓取同一条归一管线。
1049
+
1050
+ 调用方是 :mod:`session_page`(读会话当前页的 DOM)与测试夹具:正文清洗与截断只写在
1051
+ :func:`to_payload` 一处,离线进来的 HTML 不许绕过它。
1052
+ """
929
1053
  from scrapling.engines.toolbelt.custom import Response
930
1054
 
931
1055
  return Response(
@@ -939,45 +1063,33 @@ def _fake_response(html: str, url: str, status: int) -> Any:
939
1063
  )
940
1064
 
941
1065
 
942
- def extract(args: dict[str, Any]) -> dict[str, Any]:
943
- """对一段已有 HTML 做抽取,不发任何网络请求。
1066
+ def _adaptive_kwargs(args: dict[str, Any], url: str) -> dict[str, Any]:
1067
+ """按部署表态给出 adaptive 指纹库的 storage 与 storage_args。
944
1068
 
945
- :param args: 协议参数
946
- :returns: 归一后的载荷
1069
+ ``deployment.adaptiveStorage`` 只认 ``sqlite``(默认)与 ``redis``;Redis 那一支把连接
1070
+ 串与按注册域分桶的 ``url`` 一起交给 ``RedisStorageSystem``,客户端不可达时翻成带码的
1071
+ ``ADAPTIVE_STORAGE_UNAVAILABLE``,而不是让整次抽取以裸异常收场。
947
1072
  """
948
- html = args.get("html")
949
- if not isinstance(html, str):
950
- raise AdapterError("BAD_ARGS", "html must be a string")
951
- extraction_type, css_selector, main_content_only, limit = _extraction(args)
952
- status = args.get("status", 200)
953
- if not isinstance(status, int) or isinstance(status, bool):
954
- raise AdapterError("BAD_ARGS", "status must be an integer")
955
- response = _fake_response(html, str(args.get("url") or "about:blank"), status)
956
- return to_payload(
957
- response,
958
- extraction_type=extraction_type,
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 选择,返回命中的文本与少量属性。
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
968
1084
 
969
- 这正是 dsh 内置 ``web_fetch`` 结构上做不到的那部分:它只能给一整块 Markdown,
970
- 这里给的是选择器命中的具体内容。
1085
+ return {
1086
+ "storage": RedisStorageSystem,
1087
+ "storage_args": {"redis_url": redis_url or DEFAULT_REDIS_URL, "url": url},
1088
+ }
971
1089
 
972
- ``adaptive`` 打开时走 Scrapling 的自愈选择器:命中成功就把首个元素的指纹存库,
973
- 站点改版后同一个选择器直接命中失败时,按指纹重定位。存储文件固定在 sidecar 的
974
- 工作目录(部署侧的 ``dataDir``),键按 ``url`` 的注册域分桶 —— 所以重定位还要求
975
- 给 ``url``;不给就全落在 ``default`` 桶里,跨站点共用一份指纹。
976
1090
 
977
- ``maxContentChars`` 是这条路径的预算,与抓取类工具同源:``limit`` 数的是**条数**,
978
- 而十条十万字的正文照样能把模型上下文撑爆。所以逐条累计字符,超了就地截断并置
979
- ``truncated`` —— 总条数与单条长度是两根独立的轴,只压一根等于没压。
980
- """
1091
+ def select(args: dict[str, Any]) -> dict[str, Any]:
1092
+ """对已有 HTML 做选择,返回命中文本、属性或多字段行。"""
981
1093
  from scrapling.parser import Selector
982
1094
 
983
1095
  html = args.get("html")
@@ -989,35 +1101,126 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
989
1101
  attribute = args.get("attribute")
990
1102
  if attribute is not None and not isinstance(attribute, str):
991
1103
  raise AdapterError("BAD_ARGS", "attribute must be a string or null")
992
- adaptive = bool(args.get("adaptive", False))
993
1104
  url = args.get("url")
994
1105
  if url is not None and not isinstance(url, str):
995
1106
  raise AdapterError("BAD_ARGS", "url must be a string or null")
996
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 = ""
997
1177
  if adaptive:
998
1178
  # storage_args 必须把 url 一起带上:Scrapling 对「给了部分 storage_args」是整体
999
1179
  # 替换而不是补齐,漏了 url 全部指纹都会落进 default 桶。url 为空时也显式传空串,
1000
1180
  # 存储层把它归入 default 桶(StorageSystemMixin 对空值有兜底)。
1001
- page = Selector(
1002
- html,
1003
- url=url or "",
1004
- adaptive=True,
1005
- storage_args={"storage_file": ADAPTIVE_STORAGE_FILE, "url": url or ""},
1006
- )
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}"
1007
1194
  else:
1008
- page = Selector(html)
1195
+ page = Selector(html, url=url or "")
1196
+ nodes, notice = query_nodes(page, use_adaptive=False)
1009
1197
 
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
1198
  limit = _positive_int(args.get("limit"), "limit", 200)
1019
1199
  budget = _positive_int(args.get("maxContentChars"), "maxContentChars", DEFAULT_MAX_CONTENT_CHARS)
1020
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
+ }
1021
1224
 
1022
1225
  matches: list[dict[str, Any]] = []
1023
1226
  spent = 0
@@ -1025,18 +1228,24 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1025
1228
  for node in nodes:
1026
1229
  if len(matches) >= limit:
1027
1230
  break
1028
- item: dict[str, Any] = {"tag": node.tag}
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
+ )
1029
1239
  field = "value" if attribute else "text"
1030
- item[field] = str(node.attrib.get(attribute, "")) if attribute else str(node.get_all_text(strip=True))
1031
- if include_attributes:
1032
- item["attributes"] = {str(key): str(value) for key, value in node.attrib.items()}
1240
+ value = str(item.get(field, ""))
1033
1241
  # 先按剩余额度截再计入已花:一条超长正文不该把整份预算吃光,也不该在预算只剩
1034
1242
  # 一位时还能整条通过。
1035
1243
  room = max(0, budget - spent)
1036
- if len(item[field]) > room:
1037
- item[field] = item[field][:room]
1244
+ if len(value) > room:
1245
+ value = value[:room]
1038
1246
  clipped = True
1039
- spent += len(item[field])
1247
+ item[field] = value
1248
+ spent += len(value)
1040
1249
  matches.append(item)
1041
1250
  if spent >= budget:
1042
1251
  clipped = True
@@ -1045,6 +1254,7 @@ def select(args: dict[str, Any]) -> dict[str, Any]:
1045
1254
  "count": len(nodes),
1046
1255
  "truncated": clipped or len(nodes) > len(matches),
1047
1256
  "matches": _jsonable(matches),
1257
+ "notice": notice,
1048
1258
  }
1049
1259
 
1050
1260
 
@@ -1095,6 +1305,21 @@ def _probe_browser(module_name: str) -> bool:
1095
1305
  return True
1096
1306
 
1097
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
+
1098
1323
  def capabilities() -> dict[str, Any]:
1099
1324
  """报告本进程当前具备的能力,供 Host 侧决定注册哪些工具。"""
1100
1325
  report: dict[str, Any] = {
@@ -1112,20 +1337,46 @@ def capabilities() -> dict[str, Any]:
1112
1337
  # 0.5 只剩 patchright 那一套浏览器,所以这一项就是「浏览器抓取能不能用」的全部答案 ——
1113
1338
  # 0.4.15 时代那两个「普通浏览器 / 反检测浏览器」各自探测的口径已经没有第二个引擎可标。
1114
1339
  report["browser"] = _probe_browser("patchright.sync_api")
1340
+ # 浏览器守卫覆盖面的那一半(WebSocket 握手)在这里报出:拦不住时 install 只会往 stderr
1341
+ # 记一行,而那要等第一个页面建起来才看得见 —— 排障的人得在装载阶段就知道。
1342
+ report["websocketGuard"] = _websocket_guard_capability()
1115
1343
  # 出口如实上报:用户得能一眼看出抓取会从哪里出去、以及本包到底有没有在管这件事。
1116
1344
  # server 只含 scheme://host:port,凭据不出现(见 guard.proxy_settings)。
1117
1345
  report["proxy"] = guard.proxy_settings()
1118
1346
  return report
1119
1347
 
1120
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
+
1121
1370
  METHODS = {
1122
1371
  "ping": lambda _args: {"pong": True},
1123
1372
  "capabilities": lambda _args: capabilities(),
1124
1373
  "fetch": fetch,
1125
1374
  "render": render,
1126
1375
  "capture": capture,
1127
- "extract": extract,
1128
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,
1129
1380
  }
1130
1381
 
1131
1382
 
@@ -1239,6 +1490,10 @@ class _SessionWorker:
1239
1490
  self._jobs.put(None)
1240
1491
  self._thread.join(timeout=5.0)
1241
1492
 
1493
+ def alive(self) -> bool:
1494
+ """属主线程是否还在跑(T10 的 ``alive`` 判据:只读,不改动任何状态)。"""
1495
+ return not self._closed.is_set() and self._thread.is_alive()
1496
+
1242
1497
 
1243
1498
  def _new_session_id() -> str:
1244
1499
  """生成一个短的会话 id。
@@ -1388,6 +1643,9 @@ def session_open(args: dict[str, Any]) -> dict[str, Any]:
1388
1643
  "closer": closer, # 关它用的对象(static 是 wrapper,浏览器是自身)
1389
1644
  "type": kind,
1390
1645
  "created_at": datetime.now(timezone.utc).isoformat(),
1646
+ # T10 的非敏感设置摘要:在开场时把生效值记下来,session.list 不必回头去
1647
+ # 猜(凭据面永远不进这份摘要)。
1648
+ "settings": _session_settings(kind, args),
1391
1649
  # 同一把锁:占位时建的那把,盖回来而不是新建 —— 新建会让构造期与使用期各锁各的。
1392
1650
  "lock": entry_lock,
1393
1651
  # browser/stealth 的专属执行线程;static 为 None(见 _SessionWorker 的说明)。
@@ -1445,6 +1703,9 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1445
1703
  session = entry["session"]
1446
1704
  extraction_type, css_selector, main_content_only, limit = _extraction(args)
1447
1705
  url = _url(args)
1706
+ # 这两枚在载荷阶段才用到;提前读一次,让协议对表看到它们不是死键。
1707
+ strip_inline_images = _strip_inline_images(args)
1708
+ include_metadata = bool(args.get("includeMetadata", False))
1448
1709
 
1449
1710
  # 一份会话同一时刻只服务一个请求:static 靠 entry 锁,浏览器会话靠属主线程天然串行。
1450
1711
  # 两种实现也都对「多线程同时用同一份会话」零容忍 —— Playwright 的同步 API 靠 greenlet
@@ -1458,7 +1719,19 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1458
1719
  allowed, reason = guard.url_allowed(url)
1459
1720
  if not allowed:
1460
1721
  raise AdapterError("URL_BLOCKED", f"{url}: {reason}")
1461
- response = session.get(url, **_static_params(args, url))
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)
1462
1735
  else:
1463
1736
  # 浏览器会话的代理在开场时就定死了(见 _make_session),这里不再逐 URL
1464
1737
  # 覆盖 —— 覆盖的做法是新建 context,cookie 与登录态会随之清空。
@@ -1480,7 +1753,14 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1480
1753
  #
1481
1754
  # 空的没给(`{}` / `[]` / null)不算写意图:模型「不带任何请求头」时传的就是空表,
1482
1755
  # 为它报一条错等于把一个无害的调用说成非法。
1483
- for key, hint in (("headers", "extraHeaders"), ("retries", "scrapling_session_open")):
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
+ ):
1484
1764
  if args.get(key) not in (None, {}, []):
1485
1765
  raise AdapterError(
1486
1766
  "BAD_ARGS",
@@ -1503,30 +1783,192 @@ def session_fetch(args: dict[str, Any]) -> dict[str, Any]:
1503
1783
  css_selector=css_selector,
1504
1784
  main_content_only=main_content_only,
1505
1785
  max_content_chars=limit,
1506
- strip_inline_images=_strip_inline_images(args),
1786
+ strip_inline_images=strip_inline_images,
1787
+ include_metadata=include_metadata,
1507
1788
  )
1508
1789
  payload["sessionId"] = args.get("sessionId")
1509
1790
  return payload
1510
1791
 
1511
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
+
1512
1945
  def session_list(_args: dict[str, Any]) -> dict[str, Any]:
1513
1946
  """列出当前所有会话(不含任何凭据)。
1514
1947
 
1948
+ 每行除 id / type / createdAt 之外还带 ``alive``、``settings``(非敏感设置摘要)与
1949
+ ``poolStats``(浏览器会话取得到页池统计时才给;取不到就省略,绝不因此让 list 失败)。
1950
+
1515
1951
  :param _args: 协议参数,本方法不用
1516
1952
  :returns: 会话列表
1517
1953
  """
1518
1954
  # 字典遍历期间被别的线程插入/删除会抛 RuntimeError,而那正是 bridge 多 worker 下的
1519
1955
  # 常态。进锁里把清单复制出来,遍历就与并发改写无关。
1520
1956
  with _SESSION_LOCK:
1521
- rows = [
1522
- {
1523
- "sessionId": session_id,
1524
- "sessionType": entry["type"],
1525
- # 构造中的条目还没有创建时间;报空串而不是 KeyError。
1526
- "createdAt": entry.get("created_at", ""),
1527
- }
1528
- for session_id, entry in _SESSIONS.items()
1529
- ]
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)
1530
1972
  return {"sessions": rows}
1531
1973
 
1532
1974
 
@@ -1604,7 +2046,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
1604
2046
  entry = _get_session(session_id)
1605
2047
  if entry["type"] == "static":
1606
2048
  raise AdapterError("BAD_ARGS", "static sessions keep no network history")
1607
- pattern, entries, include_body, body_chars = _network_read(args)
2049
+ query = _network_read(args)
1608
2050
  recorder = getattr(entry["session"], "network", None)
1609
2051
  if recorder is None or not getattr(recorder, "enabled", False):
1610
2052
  raise AdapterError(
@@ -1615,15 +2057,7 @@ def session_network(args: dict[str, Any]) -> dict[str, Any]:
1615
2057
  worker: _SessionWorker | None = entry["worker"]
1616
2058
  if worker is None: # pragma: no cover —— 浏览器条目必有属主线程
1617
2059
  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
- )
2060
+ matches = worker.run(lambda: _network_summary(recorder, query=query))
1627
2061
  return {"sessionId": session_id, "count": len(matches), "matches": matches}
1628
2062
 
1629
2063
 
@@ -1679,6 +2113,10 @@ def _session_state(args: dict[str, Any], *, saving: bool) -> dict[str, Any]:
1679
2113
  try:
1680
2114
  if saving:
1681
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)
1682
2120
  else:
1683
2121
  worker.run(lambda: session.load_state(target))
1684
2122
  except Exception as error: # 上游的文件/JSON 错误一律翻成可路由的码
@@ -1723,6 +2161,10 @@ METHODS.update(
1723
2161
  "session.list": session_list,
1724
2162
  "session.close": session_close,
1725
2163
  "session.network": session_network,
2164
+ "session.read": session_read,
2165
+ "session.act": session_act,
2166
+ "download": download,
2167
+ "screenshot": screenshot,
1726
2168
  "session.state_save": session_state_save,
1727
2169
  "session.state_load": session_state_load,
1728
2170
  }