@jayyuen66/dsh-scrapling 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +84 -3
- package/LICENSE +1 -1
- package/README.md +15 -15
- package/README.zh-CN.md +13 -13
- package/THIRD_PARTY_NOTICES.md +32 -10
- package/bin/dsh-scrapling.mjs +118 -11
- package/client.js +110 -35
- package/docs/DETAIL.md +41 -0
- package/docs/DETAIL.zh.md +41 -0
- package/host.js +14 -30
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +61 -47
- package/py/adapters.py +30 -8
- package/py/bridge.py +88 -18
- package/py/crawl.py +69 -27
- package/py/extraction.py +67 -21
- package/py/guard.py +55 -24
- package/py/media.py +30 -9
- package/py/redact.py +20 -2
- package/py/redis_storage.py +92 -31
- package/py/search.py +9 -2
- package/py/session_page.py +57 -24
package/py/extraction.py
CHANGED
|
@@ -17,6 +17,41 @@ def _json_len(value: Any) -> int:
|
|
|
17
17
|
return len(json.dumps(value, ensure_ascii=False))
|
|
18
18
|
|
|
19
19
|
|
|
20
|
+
def _fit_text(text: str, available: int) -> str:
|
|
21
|
+
"""把文本收到 JSON 序列化后不超过 available 个字符;预算不足时给空串。
|
|
22
|
+
|
|
23
|
+
按字符裁再量一次是不够的:JSON 会转义引号/反斜杠/控制字符,裁到 N 个字符的串
|
|
24
|
+
序列化后可能远超 N。这里直接按序列化长度二分,保证返回值的 json 长度落在预算内。
|
|
25
|
+
"""
|
|
26
|
+
if available < _json_len(""):
|
|
27
|
+
return ""
|
|
28
|
+
if _json_len(text) <= available:
|
|
29
|
+
return text
|
|
30
|
+
low, high = 0, len(text)
|
|
31
|
+
while low < high:
|
|
32
|
+
middle = (low + high + 1) // 2
|
|
33
|
+
if _json_len(text[:middle]) <= available:
|
|
34
|
+
low = middle
|
|
35
|
+
else:
|
|
36
|
+
high = middle - 1
|
|
37
|
+
return text[:low]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _json_value_within(value: Any, room: int) -> tuple[Any, int, bool]:
|
|
41
|
+
"""把值收进 room 的 JSON 预算;返回 (值, 实际长度, 是否被裁)。
|
|
42
|
+
|
|
43
|
+
字符串按序列化长度收缩;其它形态(列表、对象)没有便宜的收缩方式,超预算时
|
|
44
|
+
降级为 null —— 留着整段会让调用方拿到的载荷远超 maxContentChars。
|
|
45
|
+
"""
|
|
46
|
+
size = _json_len(value)
|
|
47
|
+
if size <= room:
|
|
48
|
+
return value, size, False
|
|
49
|
+
if isinstance(value, str) and room >= _json_len(""):
|
|
50
|
+
fitted = _fit_text(value, room)
|
|
51
|
+
return fitted, _json_len(fitted), True
|
|
52
|
+
return None, _json_len(None), True
|
|
53
|
+
|
|
54
|
+
|
|
20
55
|
def _resolve_url(page: Any, value: str) -> str:
|
|
21
56
|
"""把相对地址拼成绝对地址;空值或拼不出来时保留原值。"""
|
|
22
57
|
if not value:
|
|
@@ -35,7 +70,7 @@ def _query_type(selector: str, query_type: str | None, use_xpath: bool) -> str:
|
|
|
35
70
|
def query_nodes(
|
|
36
71
|
page: Any,
|
|
37
72
|
selector: str,
|
|
38
|
-
query_type: str =
|
|
73
|
+
query_type: str | None = None,
|
|
39
74
|
*,
|
|
40
75
|
use_xpath: bool = False,
|
|
41
76
|
partial: bool = False,
|
|
@@ -199,23 +234,21 @@ def collect_fields(
|
|
|
199
234
|
rows: list[dict[str, Any]] = []
|
|
200
235
|
spent = 0
|
|
201
236
|
truncated = False
|
|
202
|
-
|
|
237
|
+
node_iter = iter(nodes)
|
|
238
|
+
for node in node_iter:
|
|
203
239
|
row: dict[str, Any] = {}
|
|
204
240
|
for name, spec in fields.items():
|
|
205
241
|
value = field_value(node, spec, page=page, resolve_urls=resolve_urls)
|
|
206
242
|
room = max(0, max_content_chars - spent)
|
|
207
|
-
size =
|
|
208
|
-
|
|
209
|
-
if isinstance(value, str):
|
|
210
|
-
# JSON 字符串带两个引号;留出它们再把正文裁到剩余预算。
|
|
211
|
-
value = value[: max(0, room - 2)]
|
|
212
|
-
size = _json_len(value)
|
|
213
|
-
truncated = True
|
|
243
|
+
value, size, dropped = _json_value_within(value, room)
|
|
244
|
+
truncated = truncated or dropped
|
|
214
245
|
spent += size
|
|
215
246
|
row[str(name)] = value
|
|
216
247
|
rows.append(row)
|
|
217
248
|
if spent >= max_content_chars:
|
|
218
|
-
|
|
249
|
+
# 只有确实还有下一条时才算截断:最后一条刚好用尽预算不是截断。
|
|
250
|
+
if next(node_iter, None) is not None:
|
|
251
|
+
truncated = True
|
|
219
252
|
break
|
|
220
253
|
return rows, truncated
|
|
221
254
|
|
|
@@ -234,11 +267,13 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
234
267
|
if url is not None and not isinstance(url, str):
|
|
235
268
|
raise ValueError("url must be a string or null")
|
|
236
269
|
query_type = args.get("queryType")
|
|
237
|
-
if query_type is not None
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
270
|
+
if query_type is not None:
|
|
271
|
+
if not isinstance(query_type, str):
|
|
272
|
+
raise ValueError("queryType must be a string")
|
|
273
|
+
if query_type not in ("css", "xpath", "text", "regex", "similar"):
|
|
274
|
+
raise ValueError(f"unknown queryType: {query_type}")
|
|
275
|
+
# 缺省留 None 交给 query_nodes 归一:显式 queryType 优先,其次 useXpath,最后 css。
|
|
276
|
+
# 这里先落成 "css" 会让调用方传的 useXpath 永远失效("//p" 被当 CSS 选择器,命中 0)。
|
|
242
277
|
limit = _positive_int(args.get("limit"), "limit", 200)
|
|
243
278
|
budget = _positive_int(args.get("maxContentChars"), "maxContentChars", 200_000)
|
|
244
279
|
include_ancestors = bool(args.get("includeAncestors", True))
|
|
@@ -259,16 +294,13 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
259
294
|
matches: list[dict[str, Any]] = []
|
|
260
295
|
spent = 0
|
|
261
296
|
truncated = False
|
|
262
|
-
|
|
297
|
+
node_iter = iter(nodes)
|
|
298
|
+
for node in node_iter:
|
|
263
299
|
if len(matches) >= limit:
|
|
264
300
|
truncated = True
|
|
265
301
|
break
|
|
266
302
|
text = str(node.get_all_text(strip=True))
|
|
267
303
|
room = max(0, budget - spent)
|
|
268
|
-
if len(text) > room:
|
|
269
|
-
text = text[:room]
|
|
270
|
-
truncated = True
|
|
271
|
-
spent += len(text)
|
|
272
304
|
item: dict[str, Any] = {
|
|
273
305
|
"tag": str(getattr(node, "tag", "") or ""),
|
|
274
306
|
"text": text,
|
|
@@ -289,9 +321,23 @@ def locate(args: dict[str, Any]) -> dict[str, Any]:
|
|
|
289
321
|
else []
|
|
290
322
|
),
|
|
291
323
|
}
|
|
324
|
+
size = _json_len(item)
|
|
325
|
+
if size > room:
|
|
326
|
+
# 预算按整条载荷算:attributes、四个选择器与 ancestors 都占字符,只量 text
|
|
327
|
+
# 会让真实返回体远超 maxContentChars。先把正文收到剩余预算,再复核一次。
|
|
328
|
+
fixed = _json_len({**item, "text": ""})
|
|
329
|
+
item["text"] = _fit_text(text, max(0, room - fixed))
|
|
330
|
+
size = _json_len(item)
|
|
331
|
+
truncated = True
|
|
332
|
+
if size > room:
|
|
333
|
+
# 连不含正文的固定结构都放不下:这一条不再进结果,预算到此为止。
|
|
334
|
+
break
|
|
335
|
+
spent += size
|
|
292
336
|
matches.append(item)
|
|
293
337
|
if spent >= budget:
|
|
294
|
-
|
|
338
|
+
# 只有确实还有下一条时才算截断:最后一条刚好用尽预算不是截断。
|
|
339
|
+
if next(node_iter, None) is not None:
|
|
340
|
+
truncated = True
|
|
295
341
|
break
|
|
296
342
|
return {
|
|
297
343
|
"count": len(nodes),
|
package/py/guard.py
CHANGED
|
@@ -150,6 +150,14 @@ def configure(
|
|
|
150
150
|
ALLOWED_HOSTS = allowed_hosts
|
|
151
151
|
if nat64_prefixes is not None:
|
|
152
152
|
EXTRA_NAT64_PREFIXES = nat64_prefixes
|
|
153
|
+
for raw in nat64_prefixes:
|
|
154
|
+
try:
|
|
155
|
+
network = ipaddress.ip_network(raw, strict=True)
|
|
156
|
+
except ValueError:
|
|
157
|
+
_log(f"ignoring an invalid extra NAT64 prefix {raw!r}")
|
|
158
|
+
continue
|
|
159
|
+
if not isinstance(network, ipaddress.IPv6Network) or network.prefixlen not in _NAT64_EMBEDDED_OFFSET:
|
|
160
|
+
_log(f"ignoring an unsupported extra NAT64 prefix {raw!r} (need /40, /48, /56, /64 or /96)")
|
|
153
161
|
if allow_write_methods is not None:
|
|
154
162
|
ALLOW_WRITE_METHODS = allow_write_methods
|
|
155
163
|
if allow_browser_actions is not None:
|
|
@@ -228,7 +236,7 @@ def configure_from_env() -> None:
|
|
|
228
236
|
PROXY_URL = ""
|
|
229
237
|
if _PAC_NOTICE:
|
|
230
238
|
_log(
|
|
231
|
-
f"system proxy is a PAC script ({_PAC_NOTICE}); it is not evaluated here — "
|
|
239
|
+
f"system proxy is a PAC script ({redact_url_secrets(_PAC_NOTICE)}); it is not evaluated here — "
|
|
232
240
|
f"set {PROXY_ENV} (the settings card's proxy) to the proxy address you want"
|
|
233
241
|
)
|
|
234
242
|
if _SYSTEM_PROXIES and not (PROXY_URL or _ENV_PROXIES):
|
|
@@ -422,6 +430,11 @@ def _host_matches(host: str, entry: str) -> bool:
|
|
|
422
430
|
:param entry: 清单里的一项(可能带前导 ``.`` 或 ``*``)
|
|
423
431
|
:returns: 是否命中
|
|
424
432
|
"""
|
|
433
|
+
if entry.strip() == "*":
|
|
434
|
+
# 整条星号是「全部绕过」。不放这里认它,它会被 lstrip 成空串再落到
|
|
435
|
+
# not item 那条假分支上 —— default_proxy 单独特判过它,两条路于是对同一份
|
|
436
|
+
# 配置给出相反答案(会话直连、静态抓取仍走代理)。
|
|
437
|
+
return True
|
|
425
438
|
item = entry.strip().lower().lstrip("*")
|
|
426
439
|
if not item:
|
|
427
440
|
return False
|
|
@@ -736,47 +749,59 @@ def effective_ip(
|
|
|
736
749
|
# 检测合成解析器用的控制域名:与用户的目标无关,答案只反映解析器本身的行为。
|
|
737
750
|
CONTROL_HOSTS: tuple[str, ...] = ("example.com", "www.iana.org", "www.wikipedia.org")
|
|
738
751
|
|
|
739
|
-
#
|
|
740
|
-
|
|
752
|
+
# 检测结果:认出的那个合成池;只算一次并缓存。None = 没有认出(或控制答案不构成单一池)。
|
|
753
|
+
_SYNTHETIC_POOL: ipaddress.IPv4Network | None = None
|
|
741
754
|
|
|
742
755
|
|
|
743
|
-
def detect_synthetic_resolver() ->
|
|
744
|
-
"""
|
|
756
|
+
def detect_synthetic_resolver() -> ipaddress.IPv4Network | None:
|
|
757
|
+
"""判断当前解析器是不是在合成地址,并给出要放宽到的那**一个**池。
|
|
745
758
|
|
|
746
759
|
依据是 fake-ip 的指纹:**所有**主机名都被指到同一个非公网小池里。实测在一台开着 TUN +
|
|
747
760
|
fake-ip 的机器上,example.com / github.com / wikipedia.org / echarts.apache.org /
|
|
748
761
|
www.apple.com 全部落在 198.18.0.0/15 内且互不相同,而 IP 字面量原样不动。
|
|
749
762
|
|
|
750
|
-
|
|
751
|
-
|
|
763
|
+
每个控制域名都要有答案,且全部答案落在**同一个**已知池里;跨池分流或有一枚落在池外都
|
|
764
|
+
判否。100.64.0.0/10 同时是 Tailscale 等真实内网常用的 CGNAT 段,拿另一个池的检测结果
|
|
765
|
+
把这一整段放宽,会让指向真实 ``100.64.x.x`` 的域名通过闸门。判否只让守卫维持最严,
|
|
766
|
+
不会误放行。
|
|
752
767
|
|
|
753
|
-
:returns:
|
|
768
|
+
:returns: 认出的合成池;判否时 None
|
|
754
769
|
"""
|
|
755
|
-
global
|
|
756
|
-
if
|
|
757
|
-
return
|
|
770
|
+
global _SYNTHETIC_POOL # noqa: PLW0603 —— 缓存一次即可
|
|
771
|
+
if _SYNTHETIC_POOL is not None:
|
|
772
|
+
return _SYNTHETIC_POOL
|
|
758
773
|
resolved: list[str] = []
|
|
759
774
|
for host in CONTROL_HOSTS:
|
|
760
775
|
try:
|
|
761
776
|
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
|
|
762
777
|
except OSError:
|
|
763
|
-
|
|
764
|
-
|
|
778
|
+
return None
|
|
779
|
+
addresses = [str(info[4][0]) for info in infos]
|
|
780
|
+
# 每个域名都要有答案:只校验总数时,一个域名回三条、另外两个解析失败也能凑够 3,
|
|
781
|
+
# 那三条同源答案不构成「所有主机名都被指到同一个池」的指纹。
|
|
782
|
+
if not addresses:
|
|
783
|
+
return None
|
|
765
784
|
# getaddrinfo 的答案元素是 str | int(sockaddr 的形状),而这里只要地址串。
|
|
766
|
-
resolved.extend(
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
return
|
|
785
|
+
resolved.extend(addresses)
|
|
786
|
+
# 全指向同一处(解析器坏了)不当成 fake-ip。
|
|
787
|
+
if len(set(resolved)) < 2:
|
|
788
|
+
return None
|
|
770
789
|
parsed = []
|
|
771
790
|
for item in resolved:
|
|
772
791
|
try:
|
|
773
792
|
parsed.append(ipaddress.ip_address(item))
|
|
774
793
|
except ValueError:
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
794
|
+
return None
|
|
795
|
+
if not all(not item.is_global for item in parsed):
|
|
796
|
+
return None
|
|
797
|
+
if not all(isinstance(item, ipaddress.IPv4Address) for item in parsed):
|
|
798
|
+
return None
|
|
799
|
+
# 全部答案必须落在同一个池;命中不止一个池说明解析器跨池分流,判否。
|
|
800
|
+
for pool in SYNTHETIC_POOLS:
|
|
801
|
+
if isinstance(pool, ipaddress.IPv4Network) and all(item in pool for item in parsed):
|
|
802
|
+
_SYNTHETIC_POOL = pool
|
|
803
|
+
return _SYNTHETIC_POOL
|
|
804
|
+
return None
|
|
780
805
|
|
|
781
806
|
|
|
782
807
|
def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
|
@@ -796,7 +821,8 @@ def _acceptable_resolved(item: ipaddress.IPv4Address | ipaddress.IPv6Address) ->
|
|
|
796
821
|
return True
|
|
797
822
|
if not isinstance(item, ipaddress.IPv4Address):
|
|
798
823
|
return False
|
|
799
|
-
|
|
824
|
+
synthetic_pool = detect_synthetic_resolver()
|
|
825
|
+
if synthetic_pool is not None and item in synthetic_pool:
|
|
800
826
|
return True
|
|
801
827
|
return bool(SYNTHETIC_NETWORKS) and any(item in network for network in SYNTHETIC_NETWORKS)
|
|
802
828
|
|
|
@@ -901,7 +927,12 @@ def url_allowed(url: str, *, websocket: bool = False) -> tuple[bool, str]:
|
|
|
901
927
|
:param websocket: 按 WebSocket 握手的口径判(认 ws/wss);发出请求的那几条路径都不传
|
|
902
928
|
:returns: (是否允许, 原因);允许时原因为空串
|
|
903
929
|
"""
|
|
904
|
-
|
|
930
|
+
try:
|
|
931
|
+
parsed = urlparse(url)
|
|
932
|
+
except ValueError:
|
|
933
|
+
# 畸形 URL(如 http://[::1 缺少右括号)在 urlparse 里就抛 ValueError。
|
|
934
|
+
# 契约是「返回 (False, reason)」,让异常漏出去会把一个坏输入变成调用方的崩溃。
|
|
935
|
+
return False, "URL is malformed"
|
|
905
936
|
# ws/wss 与 http/https 走同一套地址判定。WebSocket 握手是独立路由,page.route 拦不到,
|
|
906
937
|
# 这里不认它就等于把公网 WebSocket 一起杀了 —— 不少站点的实时数据就靠它。
|
|
907
938
|
# 而真正**发出请求**的那几条路径(fetch/crawl/download/session)不认 ws:它们不会用
|
package/py/media.py
CHANGED
|
@@ -229,15 +229,16 @@ def _download_via_stream(
|
|
|
229
229
|
try:
|
|
230
230
|
with open(temporary, "wb") as sink:
|
|
231
231
|
for chunk in response.iter_content(chunk_size=_DOWNLOAD_CHUNK_BYTES):
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
total += len(chunk)
|
|
235
|
-
if total > limit:
|
|
232
|
+
# 先判后写:写盘再判会让落盘字节超过上限最多一个块(64 KiB)。
|
|
233
|
+
if total + len(chunk) > limit:
|
|
236
234
|
raise _error(
|
|
237
235
|
"DOWNLOAD_TOO_LARGE",
|
|
238
236
|
f"download is over the {limit}-byte cap"
|
|
239
237
|
+ (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
|
|
240
238
|
)
|
|
239
|
+
sink.write(chunk)
|
|
240
|
+
digest.update(chunk)
|
|
241
|
+
total += len(chunk)
|
|
241
242
|
target = _commit_temp(directory, name, temporary)
|
|
242
243
|
except BaseException:
|
|
243
244
|
temporary.unlink(missing_ok=True)
|
|
@@ -300,10 +301,13 @@ def _download_via_browser(
|
|
|
300
301
|
browser_params["extra_headers"] = headers
|
|
301
302
|
try:
|
|
302
303
|
response = StealthyFetcher.fetch(url, **browser_params)
|
|
303
|
-
except Exception as error:
|
|
304
|
+
except Exception as error:
|
|
304
305
|
# 「Page.goto: Download is starting」:Chromium 不能把「触发下载的响应」当成一次
|
|
305
306
|
# 导航,fetch 这条路对附件/二进制响应天然走不通。换成等真实的 download 事件再把它
|
|
306
|
-
#
|
|
307
|
+
# 落盘。其它异常(超时、网络错误、路由拒绝)仍按失败上报:这里再导航一次会重复请求,
|
|
308
|
+
# 还会把真实原因盖成附件路径的异常类名。
|
|
309
|
+
if "download is starting" not in str(error).lower():
|
|
310
|
+
raise _error("DOWNLOAD_FAILED", f"download failed: {type(error).__name__}: {error}") from error
|
|
307
311
|
return _download_via_browser_attachment(
|
|
308
312
|
url,
|
|
309
313
|
name=name,
|
|
@@ -331,6 +335,21 @@ def _download_via_browser(
|
|
|
331
335
|
}
|
|
332
336
|
|
|
333
337
|
|
|
338
|
+
def _body_from_download(source: Any, limit: int) -> bytes:
|
|
339
|
+
"""读浏览器交出的下载临时文件;先量大小再读,超限时不把整份内容读进内存。
|
|
340
|
+
|
|
341
|
+
Download.path() 给的是本地临时文件,所以体积在打开之前就知道。先 read_bytes
|
|
342
|
+
再判上限意味着一个几 GB 的附件会先被整份读进内存、然后才被拒绝。
|
|
343
|
+
"""
|
|
344
|
+
if source is None:
|
|
345
|
+
raise _error("DOWNLOAD_FAILED", "download produced no local file")
|
|
346
|
+
path = Path(source)
|
|
347
|
+
size = path.stat().st_size
|
|
348
|
+
if size > limit:
|
|
349
|
+
raise _error("DOWNLOAD_TOO_LARGE", f"download is {size} bytes, over the {limit}-byte cap")
|
|
350
|
+
return path.read_bytes()
|
|
351
|
+
|
|
352
|
+
|
|
334
353
|
def _download_via_browser_attachment(
|
|
335
354
|
url: str,
|
|
336
355
|
*,
|
|
@@ -348,7 +367,7 @@ def _download_via_browser_attachment(
|
|
|
348
367
|
与一次性路径同一套网络守卫,然后等 Playwright 的 ``expect_download`` 把附件交出来。
|
|
349
368
|
"""
|
|
350
369
|
import guard
|
|
351
|
-
from adapters import page_setup
|
|
370
|
+
from adapters import AdapterError, page_setup
|
|
352
371
|
from scrapling.fetchers import StealthySession
|
|
353
372
|
|
|
354
373
|
timeout_ms = int(timeout * 1000)
|
|
@@ -369,8 +388,10 @@ def _download_via_browser_attachment(
|
|
|
369
388
|
with page.expect_download(timeout=timeout_ms) as pending, contextlib.suppress(Exception):
|
|
370
389
|
page.goto(url, wait_until="commit")
|
|
371
390
|
download = pending.value
|
|
372
|
-
|
|
373
|
-
|
|
391
|
+
body = _body_from_download(download.path(), limit)
|
|
392
|
+
except AdapterError:
|
|
393
|
+
# 超限是 caller 可读的结论(DOWNLOAD_TOO_LARGE),别再包成 DOWNLOAD_FAILED。
|
|
394
|
+
raise
|
|
374
395
|
except Exception as error:
|
|
375
396
|
raise _error(
|
|
376
397
|
"DOWNLOAD_FAILED",
|
package/py/redact.py
CHANGED
|
@@ -6,8 +6,16 @@ guard 的日志与 adapters 的网络摘要在「给日志、给模型看」之
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import re
|
|
9
10
|
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
10
11
|
|
|
12
|
+
# 畸形 URL(urlsplit 抛 ValueError)上仍要按参数名兜底:解析失败不能等于「整串放行」。
|
|
13
|
+
_QUERY_SECRET_FALLBACK = re.compile(
|
|
14
|
+
r"(?i)([?&;](?:token|key|secret|password|pwd|sig|signature|auth|session)[^=&#]*=)[^&#]*"
|
|
15
|
+
)
|
|
16
|
+
# 这些 scheme 的 ``@`` 属于地址本身(mailto/tel 之类),不是 user:pass@host 的 authority。
|
|
17
|
+
_NON_AUTHORITY_SCHEMES = frozenset({"mailto", "tel", "data", "javascript", "urn", "about", "blob"})
|
|
18
|
+
|
|
11
19
|
# 查询串里这些名字的参数装的是凭据而不是筛选条件。XHR 摘要与守卫日志都是要离开本进程的
|
|
12
20
|
# 文本——摘要进会话上下文、进第三方 provider,日志进宿主日志面——而真实站点把 access
|
|
13
21
|
# token、会话 id、签名都放在查询串里。抓到一条就等于把凭据抄进载体,而读者既用不上它、
|
|
@@ -18,6 +26,14 @@ _SECRET_QUERY_KEYS = frozenset(
|
|
|
18
26
|
"access_token",
|
|
19
27
|
"api_key",
|
|
20
28
|
"apikey",
|
|
29
|
+
"client_secret",
|
|
30
|
+
"x-api-key",
|
|
31
|
+
"x-amz-credential",
|
|
32
|
+
"x-amz-signature",
|
|
33
|
+
"x-amz-security-token",
|
|
34
|
+
"x-goog-signature",
|
|
35
|
+
"private_key",
|
|
36
|
+
"jwt",
|
|
21
37
|
"auth",
|
|
22
38
|
"auth_token",
|
|
23
39
|
"authorization",
|
|
@@ -96,13 +112,15 @@ def redact_url_secrets(raw: str) -> str:
|
|
|
96
112
|
try:
|
|
97
113
|
parsed = urlsplit(raw)
|
|
98
114
|
except ValueError:
|
|
99
|
-
return raw
|
|
115
|
+
return _QUERY_SECRET_FALLBACK.sub(r"\1<redacted>", raw)
|
|
100
116
|
# 没有 scheme 的 ``user:pass@host:8080`` 会被 urlsplit 读成 scheme='user'、
|
|
101
117
|
# path='pass@host:8080':netloc 为空,下面按 netloc 摘 userinfo 的那一步什么都不做,
|
|
102
118
|
# 整条代理口令于是原样漏进日志(PROXY_URL 不可用那条日志正是这么来的)。这种形态的
|
|
103
119
|
# authority 落在 path 的第一段上,按同一套规则摘掉;误读成 scheme 的那段一起丢弃。
|
|
104
120
|
authority, slash, rest = parsed.path.partition("/")
|
|
105
|
-
standalone_authority =
|
|
121
|
+
standalone_authority = (
|
|
122
|
+
not parsed.netloc and "@" in authority and parsed.scheme.lower() not in _NON_AUTHORITY_SCHEMES
|
|
123
|
+
)
|
|
106
124
|
if standalone_authority:
|
|
107
125
|
path = authority.rpartition("@")[2] + slash + rest
|
|
108
126
|
netloc = ""
|
package/py/redis_storage.py
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
14
|
from functools import lru_cache
|
|
15
|
-
from threading import
|
|
15
|
+
from threading import Lock
|
|
16
16
|
from typing import Any, Callable, Optional
|
|
17
17
|
from urllib.parse import urlsplit
|
|
18
18
|
|
|
@@ -22,39 +22,77 @@ DEFAULT_REDIS_URL = "redis://127.0.0.1:6379/0"
|
|
|
22
22
|
KEY_PREFIX = "scrapling:adaptive"
|
|
23
23
|
DEFAULT_TIMEOUT_SECONDS = 2.0
|
|
24
24
|
|
|
25
|
+
# 客户端按 (连接串, 超时) 复用:上游要求存储类用 ``lru_cache`` 包一层(它检查 ``__wrapped__``),
|
|
26
|
+
# 而 adapters 的 ``storage_args`` 里带着**整页 URL**,所以每抓一个新页面就会新建一个存储实例。
|
|
27
|
+
# 连接池若跟着实例走,就是每页新开一池、上一个池被挤出缓存时没人关(连接要等 GC 才释放)。
|
|
28
|
+
# 按连接串复用之后,实例的多少不再放大连接数。
|
|
29
|
+
_CLIENT_CACHE: dict[tuple[str, float], Any] = {}
|
|
30
|
+
_CLIENT_LOCK = Lock()
|
|
31
|
+
|
|
25
32
|
|
|
26
33
|
class RedisUnavailable(RuntimeError):
|
|
27
34
|
"""Redis 不可用或客户端缺失;调用方把它翻成带码的失败。"""
|
|
28
35
|
|
|
29
36
|
|
|
30
37
|
def redacted_redis_url(raw: str) -> str:
|
|
31
|
-
"""去掉 userinfo 的展示形式:口令不进日志、不进错误消息。
|
|
38
|
+
"""去掉 userinfo 的展示形式:口令不进日志、不进错误消息。
|
|
39
|
+
|
|
40
|
+
urlsplit 对非法端口**不报错**,真正抛 ValueError 的是惰性解析的 .port;本函数恰好只在
|
|
41
|
+
构造异常消息时被调用(__init__ 与 save/retrieve 的 except 分支),早先那版会让「非法
|
|
42
|
+
redisUrl」以 ValueError: Port could not be cast to integer value 顶替本函数该给的可读
|
|
43
|
+
文本,把排障引去看代码而不是看配置。所以端口解析也收进 try,解不开就写 <invalid-port>
|
|
44
|
+
——主机仍要留着,那正是要看的那一位。
|
|
45
|
+
|
|
46
|
+
IPv6 字面量的方括号由 urlsplit 剥掉(hostname 是裸 ::1),重建成 redis://::1:6379/0 就
|
|
47
|
+
不再是可复用的连接串,这里补回方括号。
|
|
48
|
+
"""
|
|
32
49
|
try:
|
|
33
50
|
parts = urlsplit(raw)
|
|
34
51
|
except ValueError:
|
|
35
52
|
return "redis://<invalid>"
|
|
36
53
|
host = parts.hostname or "<invalid>"
|
|
37
|
-
|
|
54
|
+
if ":" in host:
|
|
55
|
+
host = f"[{host}]"
|
|
56
|
+
try:
|
|
57
|
+
port = f":{parts.port}" if parts.port is not None else ""
|
|
58
|
+
except ValueError:
|
|
59
|
+
port = ":<invalid-port>"
|
|
38
60
|
database = parts.path or ""
|
|
39
61
|
return f"{parts.scheme or 'redis'}://{host}{port}{database}"
|
|
40
62
|
|
|
41
63
|
|
|
42
64
|
def _default_client(redis_url: str, *, timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS) -> Any:
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
65
|
+
# 同一 (连接串, 超时) 只建一个客户端:存储实例是每个 URL 一个(见 _CLIENT_CACHE 的说明),
|
|
66
|
+
# 连接池跟着实例走就会每页新开一池。复用之后连接数由连接串的个数决定,不由页面个数决定。
|
|
67
|
+
key = (redis_url, timeout_seconds)
|
|
68
|
+
with _CLIENT_LOCK:
|
|
69
|
+
cached = _CLIENT_CACHE.get(key)
|
|
70
|
+
if cached is not None:
|
|
71
|
+
return cached
|
|
72
|
+
try:
|
|
73
|
+
from redis import Redis
|
|
74
|
+
except ModuleNotFoundError as error:
|
|
75
|
+
# 没装客户端是**部署**的问题,不是抓取失败:点名的错误让人知道该装 adaptive-redis 包。
|
|
76
|
+
raise RedisUnavailable(
|
|
77
|
+
"the redis client is missing; install the adaptive-redis pack (pip install redis)"
|
|
78
|
+
) from error
|
|
79
|
+
# 超时要真的交给客户端:早先它只落在 self.timeout_seconds 上、全文件没有使用点,于是
|
|
80
|
+
# socket 超时一直是客户端自己的默认值(连接卡住时表现为整场抓取挂死)。
|
|
81
|
+
client = Redis.from_url(
|
|
82
|
+
redis_url,
|
|
83
|
+
decode_responses=True,
|
|
84
|
+
socket_timeout=timeout_seconds,
|
|
85
|
+
socket_connect_timeout=timeout_seconds,
|
|
86
|
+
)
|
|
87
|
+
_CLIENT_CACHE[key] = client
|
|
88
|
+
return client
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _forget_client(key: tuple[str, float], client: Any) -> None:
|
|
92
|
+
"""把这份客户端从复用表里摘掉(只摘自己那一份,别人的不动)。"""
|
|
93
|
+
with _CLIENT_LOCK:
|
|
94
|
+
if _CLIENT_CACHE.get(key) is client:
|
|
95
|
+
_CLIENT_CACHE.pop(key, None)
|
|
58
96
|
|
|
59
97
|
|
|
60
98
|
@lru_cache(1, typed=True)
|
|
@@ -79,15 +117,27 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
79
117
|
self.redis_url = redis_url
|
|
80
118
|
self.prefix = prefix
|
|
81
119
|
self.timeout_seconds = timeout_seconds
|
|
82
|
-
self.
|
|
120
|
+
self._client_key = (redis_url, timeout_seconds)
|
|
121
|
+
# 构造阶段与连接阶段分开报:工厂抛的是「谁也没连上」,ping 抛的才是「连不上」。
|
|
83
122
|
try:
|
|
84
123
|
self._client = client_factory(redis_url, timeout_seconds=timeout_seconds)
|
|
85
|
-
self._client.ping()
|
|
86
124
|
except RedisUnavailable:
|
|
87
125
|
raise
|
|
126
|
+
except TypeError:
|
|
127
|
+
# 自定义工厂的签名不接受 timeout_seconds 是**代码**问题,不是连接故障;
|
|
128
|
+
# 翻成「not reachable」会把排障引去查网络。原样抛,调用方(adapters)会带上类型名。
|
|
129
|
+
raise
|
|
130
|
+
except Exception as error:
|
|
131
|
+
raise RedisUnavailable(
|
|
132
|
+
f"redis client setup failed for {redacted_redis_url(redis_url)}: {type(error).__name__}: {error}"
|
|
133
|
+
) from error
|
|
134
|
+
try:
|
|
135
|
+
self._client.ping()
|
|
88
136
|
except Exception as error: # 连接失败的种类由客户端决定
|
|
137
|
+
# 连不上就把这份客户端从复用表里摘掉:留着它只会让下一次构造再撞同一堵墙。
|
|
138
|
+
_forget_client(self._client_key, self._client)
|
|
89
139
|
raise RedisUnavailable(
|
|
90
|
-
f"redis is not reachable at {redacted_redis_url(redis_url)}: {type(error).__name__}"
|
|
140
|
+
f"redis is not reachable at {redacted_redis_url(redis_url)}: {type(error).__name__}: {error}"
|
|
91
141
|
) from error
|
|
92
142
|
|
|
93
143
|
def _key(self, identifier: str) -> str:
|
|
@@ -100,30 +150,41 @@ class RedisStorageSystem(StorageSystemMixin):
|
|
|
100
150
|
from scrapling.core.utils import _StorageTools
|
|
101
151
|
|
|
102
152
|
payload = dumps(_StorageTools.element_to_dict(element)).decode("utf-8")
|
|
153
|
+
# 不加锁:redis-py 的客户端与连接池本身线程安全,单条 SET 也没有可被撕开的中间态;
|
|
154
|
+
# 存储层的锁只会把最多 timeout_seconds 的 socket 阻塞复制到其它线程上。
|
|
103
155
|
try:
|
|
104
|
-
|
|
105
|
-
self._client.set(self._key(identifier), payload)
|
|
156
|
+
self._client.set(self._key(identifier), payload)
|
|
106
157
|
except Exception as error:
|
|
107
158
|
raise RedisUnavailable(
|
|
108
|
-
f"redis write failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}"
|
|
159
|
+
f"redis write failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}: {error}"
|
|
109
160
|
) from error
|
|
110
161
|
|
|
111
162
|
def retrieve(self, identifier: str) -> Optional[dict[str, Any]]:
|
|
112
163
|
from orjson import loads
|
|
113
164
|
|
|
114
165
|
try:
|
|
115
|
-
|
|
116
|
-
raw = self._client.get(self._key(identifier))
|
|
166
|
+
raw = self._client.get(self._key(identifier))
|
|
117
167
|
except Exception as error:
|
|
118
168
|
raise RedisUnavailable(
|
|
119
|
-
f"redis read failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}"
|
|
169
|
+
f"redis read failed at {redacted_redis_url(self.redis_url)}: {type(error).__name__}: {error}"
|
|
120
170
|
) from error
|
|
121
171
|
if raw is None:
|
|
122
172
|
return None
|
|
123
173
|
return loads(raw)
|
|
124
174
|
|
|
125
175
|
def close(self) -> None:
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
176
|
+
"""关掉客户端,并把自己从 lru_cache 里摘掉。
|
|
177
|
+
|
|
178
|
+
第二件事是承重的:类是用 lru_cache(1) 包的(上游按 __wrapped__ 校验),关掉客户端后
|
|
179
|
+
它仍会把同一个实例发给下一次相同参数的构造,于是那份存储永久坏死——每次 save/retrieve
|
|
180
|
+
都撞一个已关闭的客户端,adapters 每页降级,没有任何自愈路径。
|
|
181
|
+
"""
|
|
182
|
+
_forget_client(self._client_key, self._client)
|
|
183
|
+
close = getattr(self._client, "close", None)
|
|
184
|
+
if callable(close):
|
|
185
|
+
close()
|
|
186
|
+
# 注意取的是模块级的包装对象:实例的 type 是**原始类**,lru 包装上的 cache_clear
|
|
187
|
+
# 只挂在模块导出的那个可调用对象上。
|
|
188
|
+
drop_cache = getattr(RedisStorageSystem, "cache_clear", None)
|
|
189
|
+
if callable(drop_cache):
|
|
190
|
+
drop_cache()
|
package/py/search.py
CHANGED
|
@@ -278,8 +278,15 @@ def _duckduckgo_target(href: str) -> str:
|
|
|
278
278
|
"""DuckDuckGo 的结果链接是 `/l/?uddg=<enc>` 跳板;取出真正的目标。"""
|
|
279
279
|
from urllib.parse import parse_qs, urlparse, urlunparse
|
|
280
280
|
|
|
281
|
-
|
|
282
|
-
|
|
281
|
+
absolute = f"https:{href}" if href.startswith("//") else href
|
|
282
|
+
parts = urlparse(absolute)
|
|
283
|
+
host = (parts.hostname or "").lower()
|
|
284
|
+
# 跳板可能以相对形式出现(netloc 为空);主机按 hostname 精确/后缀匹配,
|
|
285
|
+
# 子串判断会把 duckduckgo.com.evil.example 也当成自家跳板。
|
|
286
|
+
is_wrapper = parts.path.startswith("/l/") and (
|
|
287
|
+
host == "" or host == "duckduckgo.com" or host.endswith(".duckduckgo.com")
|
|
288
|
+
)
|
|
289
|
+
if is_wrapper:
|
|
283
290
|
target = parse_qs(parts.query).get("uddg")
|
|
284
291
|
if target:
|
|
285
292
|
return target[0]
|