@jayyuen66/dsh-scrapling 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/README.md +141 -19
- package/README.zh-CN.md +141 -19
- package/THIRD_PARTY_NOTICES.md +20 -2
- package/bin/dsh-scrapling.mjs +13 -0
- package/client.js +11 -3
- package/cordis.patch.yml +1 -1
- package/host.js +40 -36
- package/package.json +26 -9
- package/py/adapters.py +763 -267
- package/py/bridge.py +27 -4
- package/py/crawl.py +640 -90
- package/py/extraction.py +400 -0
- package/py/guard.py +120 -27
- package/py/media.py +474 -0
- package/py/redact.py +118 -0
- package/py/redis_storage.py +129 -0
- package/py/runtime-requirements.txt +49 -0
- package/py/search.py +404 -0
- package/py/session_page.py +240 -0
- package/runtime-manifest.json +16 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""会话当前页的读取。只碰 ``StealthySession`` 的 page pool,不新建浏览器。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _adapter_error(code: str, message: str, *, details: dict[str, Any] | None = None) -> Exception:
|
|
9
|
+
from adapters import AdapterError
|
|
10
|
+
|
|
11
|
+
return AdapterError(code, message, details=details)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_ACTION_TYPES = frozenset(
|
|
15
|
+
{
|
|
16
|
+
"click",
|
|
17
|
+
"move",
|
|
18
|
+
"wheel",
|
|
19
|
+
"textbox",
|
|
20
|
+
"checkbox",
|
|
21
|
+
"radio",
|
|
22
|
+
"combobox",
|
|
23
|
+
"press_key",
|
|
24
|
+
"dialog",
|
|
25
|
+
"wait_time",
|
|
26
|
+
"wait_element",
|
|
27
|
+
"wait_load",
|
|
28
|
+
}
|
|
29
|
+
)
|
|
30
|
+
_SELECTOR_ACTIONS = frozenset({"click", "textbox", "checkbox", "radio", "combobox", "wait_element"})
|
|
31
|
+
_ELEMENT_STATES = frozenset({"attached", "detached", "hidden", "visible"})
|
|
32
|
+
_LOAD_STATES = frozenset({"load", "domcontentloaded", "networkidle"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _ready_page(session: Any) -> Any:
|
|
36
|
+
"""取一个就绪页;区分「没有页」与「页都被占用」。"""
|
|
37
|
+
pool = getattr(session, "page_pool", None)
|
|
38
|
+
if pool is None:
|
|
39
|
+
raise _adapter_error("BAD_ARGS", "this session has no current page")
|
|
40
|
+
page_info = pool.get_ready_page()
|
|
41
|
+
if page_info is None:
|
|
42
|
+
if getattr(pool, "pages_count", 0) > 0:
|
|
43
|
+
raise _adapter_error("PAGE_BUSY", "the session's page is busy; retry shortly")
|
|
44
|
+
raise _adapter_error("NO_CURRENT_PAGE", "the session has not opened a page yet")
|
|
45
|
+
return page_info
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _finish_page(pool: Any, page_info: Any) -> None:
|
|
49
|
+
page = page_info.page
|
|
50
|
+
if page.is_closed():
|
|
51
|
+
pool.remove_page(page_info)
|
|
52
|
+
elif page_info in pool.pages:
|
|
53
|
+
page_info.mark_ready()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def read_current_page(
|
|
57
|
+
session: Any,
|
|
58
|
+
*,
|
|
59
|
+
extraction_type: str,
|
|
60
|
+
css_selector: str | None,
|
|
61
|
+
main_content_only: bool,
|
|
62
|
+
max_content_chars: int,
|
|
63
|
+
include_metadata: bool,
|
|
64
|
+
strip_inline_images: bool,
|
|
65
|
+
) -> dict[str, Any]:
|
|
66
|
+
"""读当前就绪页的正文;没有页或页不可用时给出明确错误码。
|
|
67
|
+
|
|
68
|
+
页面池把「没有页」与「页都被占用」分成两件事:前者是还没抓过,后者是别的请求
|
|
69
|
+
正在用这一页。两者对模型要采取的行动不同,所以不能合并成一个空正文。
|
|
70
|
+
"""
|
|
71
|
+
from adapters import _fake_response, to_payload
|
|
72
|
+
|
|
73
|
+
page_info = _ready_page(session)
|
|
74
|
+
page = page_info.page
|
|
75
|
+
try:
|
|
76
|
+
if page.is_closed():
|
|
77
|
+
raise _adapter_error("PAGE_BUSY", "the session's page has been closed")
|
|
78
|
+
html = page.content()
|
|
79
|
+
title = page.title()
|
|
80
|
+
url = page.url
|
|
81
|
+
response = _fake_response(str(html), str(url), 200)
|
|
82
|
+
payload = to_payload(
|
|
83
|
+
response,
|
|
84
|
+
extraction_type=extraction_type,
|
|
85
|
+
css_selector=css_selector,
|
|
86
|
+
main_content_only=main_content_only,
|
|
87
|
+
max_content_chars=max_content_chars,
|
|
88
|
+
strip_inline_images=strip_inline_images,
|
|
89
|
+
include_metadata=include_metadata,
|
|
90
|
+
)
|
|
91
|
+
finally:
|
|
92
|
+
_finish_page(session.page_pool, page_info)
|
|
93
|
+
return {
|
|
94
|
+
"url": payload["url"],
|
|
95
|
+
"title": str(title),
|
|
96
|
+
"content": payload["content"],
|
|
97
|
+
"truncated": payload["truncated"],
|
|
98
|
+
"notice": "the page was read from the session's current DOM, not fetched again",
|
|
99
|
+
**({"metadata": payload["metadata"]} if "metadata" in payload else {}),
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _require_selector(action: dict[str, Any], kind: str) -> str:
|
|
104
|
+
target = action.get("target")
|
|
105
|
+
if not isinstance(target, str) or not target:
|
|
106
|
+
raise _adapter_error("ACTION_INVALID", f"{kind} needs a non-empty target selector")
|
|
107
|
+
return target
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> None:
|
|
111
|
+
"""执行一个已校验的动作。"""
|
|
112
|
+
kind = str(action["type"])
|
|
113
|
+
if kind == "wait_time":
|
|
114
|
+
page.wait_for_timeout(int(action["ms"]))
|
|
115
|
+
return
|
|
116
|
+
if kind == "wait_load":
|
|
117
|
+
page.wait_for_load_state(str(action.get("state", "load")), timeout=timeout_ms)
|
|
118
|
+
return
|
|
119
|
+
if kind == "wheel":
|
|
120
|
+
page.mouse.wheel(float(action["deltaX"]), float(action["deltaY"]))
|
|
121
|
+
return
|
|
122
|
+
if kind == "dialog":
|
|
123
|
+
accept = action.get("accept", True) is not False
|
|
124
|
+
page.once("dialog", lambda dialog: dialog.accept() if accept else dialog.dismiss())
|
|
125
|
+
return
|
|
126
|
+
if kind == "press_key":
|
|
127
|
+
key = str(action.get("key", ""))
|
|
128
|
+
target = action.get("target")
|
|
129
|
+
if isinstance(target, str) and target:
|
|
130
|
+
page.locator(target).press(key, timeout=timeout_ms)
|
|
131
|
+
else:
|
|
132
|
+
page.keyboard.press(key)
|
|
133
|
+
return
|
|
134
|
+
if kind == "move" and not isinstance(action.get("target"), str):
|
|
135
|
+
page.mouse.move(float(action["x"]), float(action["y"]))
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
selector = _require_selector(action, kind)
|
|
139
|
+
locator = page.locator(selector)
|
|
140
|
+
if kind == "click":
|
|
141
|
+
locator.click(timeout=timeout_ms)
|
|
142
|
+
elif kind == "move":
|
|
143
|
+
locator.hover(timeout=timeout_ms)
|
|
144
|
+
elif kind == "textbox":
|
|
145
|
+
locator.fill(str(action.get("value", "")), timeout=timeout_ms)
|
|
146
|
+
elif kind == "checkbox":
|
|
147
|
+
if action.get("checked", True) is False:
|
|
148
|
+
locator.uncheck(timeout=timeout_ms)
|
|
149
|
+
else:
|
|
150
|
+
locator.check(timeout=timeout_ms)
|
|
151
|
+
elif kind == "radio":
|
|
152
|
+
locator.check(timeout=timeout_ms)
|
|
153
|
+
elif kind == "combobox":
|
|
154
|
+
locator.select_option(str(action.get("value", "")), timeout=timeout_ms)
|
|
155
|
+
elif kind == "wait_element":
|
|
156
|
+
locator.wait_for(state=str(action.get("state", "visible")), timeout=timeout_ms)
|
|
157
|
+
else: # pragma: no cover —— 类型白名单已挡住
|
|
158
|
+
raise _adapter_error("ACTION_INVALID", f"unknown action type: {kind}")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
|
|
162
|
+
if not isinstance(value, list) or not value:
|
|
163
|
+
raise _adapter_error("ACTION_INVALID", "actions must be a non-empty array")
|
|
164
|
+
if len(value) > max_actions:
|
|
165
|
+
raise _adapter_error("ACTION_INVALID", f"at most {max_actions} actions are allowed")
|
|
166
|
+
actions: list[dict[str, Any]] = []
|
|
167
|
+
for index, item in enumerate(value, start=1):
|
|
168
|
+
if not isinstance(item, dict):
|
|
169
|
+
raise _adapter_error("ACTION_INVALID", f"action {index} must be an object")
|
|
170
|
+
kind = item.get("type")
|
|
171
|
+
if kind not in _ACTION_TYPES:
|
|
172
|
+
raise _adapter_error("ACTION_INVALID", f"action {index} has an unknown type: {kind!r}")
|
|
173
|
+
action = dict(item)
|
|
174
|
+
if kind in _SELECTOR_ACTIONS:
|
|
175
|
+
_require_selector(action, str(kind))
|
|
176
|
+
if (
|
|
177
|
+
kind == "move"
|
|
178
|
+
and not isinstance(action.get("target"), str)
|
|
179
|
+
and (not isinstance(action.get("x"), (int, float)) or not isinstance(action.get("y"), (int, float)))
|
|
180
|
+
):
|
|
181
|
+
raise _adapter_error("ACTION_INVALID", "move needs a target or x/y coordinates")
|
|
182
|
+
if kind == "wheel" and (
|
|
183
|
+
not isinstance(action.get("deltaX"), (int, float)) or not isinstance(action.get("deltaY"), (int, float))
|
|
184
|
+
):
|
|
185
|
+
raise _adapter_error("ACTION_INVALID", "wheel needs numeric deltaX and deltaY")
|
|
186
|
+
if kind == "wait_time":
|
|
187
|
+
ms = action.get("ms")
|
|
188
|
+
if not isinstance(ms, int) or isinstance(ms, bool) or ms < 0:
|
|
189
|
+
raise _adapter_error("ACTION_INVALID", "wait_time needs a non-negative ms")
|
|
190
|
+
if kind == "wait_element":
|
|
191
|
+
state = action.get("state", "visible")
|
|
192
|
+
if state not in _ELEMENT_STATES:
|
|
193
|
+
raise _adapter_error("ACTION_INVALID", f"unknown element state: {state!r}")
|
|
194
|
+
if kind == "wait_load":
|
|
195
|
+
state = action.get("state", "load")
|
|
196
|
+
if state not in _LOAD_STATES:
|
|
197
|
+
raise _adapter_error("ACTION_INVALID", f"unknown load state: {state!r}")
|
|
198
|
+
if kind == "press_key" and not isinstance(action.get("key"), str):
|
|
199
|
+
raise _adapter_error("ACTION_INVALID", "press_key needs a key")
|
|
200
|
+
if kind == "dialog" and not isinstance(action.get("accept", True), bool):
|
|
201
|
+
raise _adapter_error("ACTION_INVALID", "dialog accept must be a boolean")
|
|
202
|
+
actions.append(action)
|
|
203
|
+
return actions
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def run_actions(
|
|
207
|
+
session: Any,
|
|
208
|
+
*,
|
|
209
|
+
actions: Any,
|
|
210
|
+
slowly: bool,
|
|
211
|
+
max_actions: int,
|
|
212
|
+
timeout_ms: int,
|
|
213
|
+
) -> dict[str, Any]:
|
|
214
|
+
"""按顺序执行结构化动作;首个失败停止并点名下标。"""
|
|
215
|
+
prepared = _validate_actions(actions, max_actions)
|
|
216
|
+
page_info = _ready_page(session)
|
|
217
|
+
page = page_info.page
|
|
218
|
+
completed = 0
|
|
219
|
+
try:
|
|
220
|
+
if page.is_closed():
|
|
221
|
+
raise _adapter_error("PAGE_BUSY", "the session's page has been closed")
|
|
222
|
+
for index, action in enumerate(prepared, start=1):
|
|
223
|
+
try:
|
|
224
|
+
_perform(page, action, timeout_ms)
|
|
225
|
+
except Exception as error:
|
|
226
|
+
raise _adapter_error(
|
|
227
|
+
"ACTION_FAILED",
|
|
228
|
+
f"action {index} ({action['type']}) failed: {type(error).__name__}: {error}",
|
|
229
|
+
details={"actionIndex": index},
|
|
230
|
+
) from error
|
|
231
|
+
completed = index
|
|
232
|
+
if slowly:
|
|
233
|
+
page.wait_for_timeout(100)
|
|
234
|
+
return {
|
|
235
|
+
"completed": completed,
|
|
236
|
+
"finalUrl": str(page.url),
|
|
237
|
+
"title": str(page.title()),
|
|
238
|
+
}
|
|
239
|
+
finally:
|
|
240
|
+
_finish_page(session.page_pool, page_info)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"darwinArm64": {
|
|
3
|
+
"platform": "darwin",
|
|
4
|
+
"arch": "arm64",
|
|
5
|
+
"pythonVersion": "3.14.9",
|
|
6
|
+
"release": "20261021",
|
|
7
|
+
"url": "https://github.com/astral-sh/python-build-standalone/releases/download/20261021/cpython-3.14.9%2B20261021-aarch64-apple-darwin-install_only.tar.gz",
|
|
8
|
+
"sha256": "226d696642a8a53d03b4d5b255b1c319b1575a6d44bd723a953c9f507755e36a",
|
|
9
|
+
"sizeBytes": 26834117
|
|
10
|
+
},
|
|
11
|
+
"unsupported": {
|
|
12
|
+
"darwin-x64": "not verified on this host",
|
|
13
|
+
"linux-x64": "not verified on this host",
|
|
14
|
+
"win32-x64": "not verified on this host"
|
|
15
|
+
}
|
|
16
|
+
}
|