@jayyuen66/dsh-scrapling 0.1.13 → 0.1.14
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 +41 -1
- package/README.md +15 -6
- package/README.zh-CN.md +15 -6
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/bin/dsh-scrapling.mjs +74 -68
- package/client.js +5 -108
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +10 -4
- package/docs/DETAIL.zh.md +10 -4
- package/host.js +31 -26
- package/package.json +6 -9
- package/py/bridge.py +41 -0
- package/py/extraction.py +68 -8
- package/py/media.py +2 -2
- package/py/redact.py +43 -8
- package/py/redis_storage.py +127 -22
- package/py/search.py +39 -27
- package/py/session_page.py +106 -23
package/py/search.py
CHANGED
|
@@ -17,6 +17,16 @@ DEFAULT_DUCKDUCKGO_ENDPOINT = "https://html.duckduckgo.com/html/"
|
|
|
17
17
|
BACKENDS = ("auto", "tavily", "bing", "brave", "serper", "duckduckgo", "searxng")
|
|
18
18
|
DEFAULT_SEARCH_RESULTS = 8
|
|
19
19
|
DEFAULT_SEARCH_TIMEOUT_SECONDS = 30.0
|
|
20
|
+
# Brave Web Search API 的 `count` 与 Tavily 的 `max_results` 都是 1..20(上游文档口径)。
|
|
21
|
+
# 上层 `lib/search-provider.ts` 的 MAX_SOURCES 是 100,会把这个值一路放到 100 ——
|
|
22
|
+
# 那两条后端拿到 100 只会判参数错,回执里看不到「被夹到 20」这件事。
|
|
23
|
+
BRAVE_MAX_COUNT = 20
|
|
24
|
+
TAVILY_MAX_RESULTS = 20
|
|
25
|
+
# 每条后端自己只发一次请求,重试交给协议层(`lib/search-provider.ts` 的 timeoutMs 是
|
|
26
|
+
# 整次调用的预算)。上游 Fetcher 默认 retries=3、retry_delay=1,一次慢后端最坏要花
|
|
27
|
+
# `3 × timeout + 2s`,比协议层先到期的超时还长 —— 于是 SEARCH_TIMEOUT 永远走不到,
|
|
28
|
+
# 模型看到的是一条含义更模糊的协议层超时。显式传 1 让两层的预算对齐。
|
|
29
|
+
SEARCH_RETRIES = 1
|
|
20
30
|
|
|
21
31
|
|
|
22
32
|
class SearchError(ValueError):
|
|
@@ -53,6 +63,15 @@ def _endpoint(value: Any, default: str, field: str) -> str:
|
|
|
53
63
|
|
|
54
64
|
def _status_error(status: int, backend: str) -> SearchError | None:
|
|
55
65
|
if status in (401, 403):
|
|
66
|
+
# SearXNG 没有 API key 这回事:它的 401/403 几乎总是「实例没开 json 输出格式」
|
|
67
|
+
# (`search.formats` 默认只有 html)。对这条后端说「检查 API key」会把人指到
|
|
68
|
+
# 一个根本不存在的配置项上。
|
|
69
|
+
if backend == "searxng":
|
|
70
|
+
return SearchError(
|
|
71
|
+
"SEARCH_AUTH",
|
|
72
|
+
"searxng answered 401/403; most instances ship with the json format disabled — "
|
|
73
|
+
"enable it in the instance's settings.yml (search.formats: [html, json])",
|
|
74
|
+
)
|
|
56
75
|
return SearchError(
|
|
57
76
|
"SEARCH_AUTH",
|
|
58
77
|
f"{backend} rejected the credentials; check the configured API key",
|
|
@@ -80,38 +99,27 @@ def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
|
|
|
80
99
|
json={
|
|
81
100
|
"api_key": key,
|
|
82
101
|
"query": query,
|
|
83
|
-
"max_results": limit,
|
|
102
|
+
"max_results": min(limit, TAVILY_MAX_RESULTS),
|
|
84
103
|
"search_depth": "basic",
|
|
85
104
|
},
|
|
86
105
|
timeout=timeout,
|
|
106
|
+
retries=SEARCH_RETRIES,
|
|
87
107
|
)
|
|
88
108
|
except Exception as error: # noqa: BLE001 —— 只翻译成带码的失败,不回显请求体
|
|
89
109
|
raise _translate(error, "tavily") from None
|
|
90
110
|
failed = _status_error(int(getattr(response, "status", 0)), "tavily")
|
|
91
111
|
if failed is not None:
|
|
92
112
|
raise failed
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
url = item.get("url")
|
|
104
|
-
if not isinstance(url, str) or not url:
|
|
105
|
-
continue
|
|
106
|
-
title = item.get("title")
|
|
107
|
-
content = item.get("content")
|
|
108
|
-
hits.append(
|
|
109
|
-
{
|
|
110
|
-
"url": url,
|
|
111
|
-
"title": title if isinstance(title, str) else "",
|
|
112
|
-
"snippet": content if isinstance(content, str) else "",
|
|
113
|
-
}
|
|
114
|
-
)
|
|
113
|
+
payload = _json_body(response, "tavily")
|
|
114
|
+
# 走与另外五条后端同一个收集器:`{}`(没有 results 键)与 `{"results": "x"}` 都收成空表,
|
|
115
|
+
# 而非对象回包已经在 _json_body 那里判成 SEARCH_FAILED 了。
|
|
116
|
+
hits = _collect(
|
|
117
|
+
payload.get("results"),
|
|
118
|
+
limit=limit,
|
|
119
|
+
url_key="url",
|
|
120
|
+
title_key="title",
|
|
121
|
+
snippet_key="content",
|
|
122
|
+
)
|
|
115
123
|
return {"backend": "tavily", "hits": hits}
|
|
116
124
|
|
|
117
125
|
|
|
@@ -120,7 +128,7 @@ def _bing(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[
|
|
|
120
128
|
from scrapling.fetchers import Fetcher
|
|
121
129
|
|
|
122
130
|
try:
|
|
123
|
-
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout)
|
|
131
|
+
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout, retries=SEARCH_RETRIES)
|
|
124
132
|
except Exception as error: # noqa: BLE001
|
|
125
133
|
raise _translate(error, "bing") from None
|
|
126
134
|
failed = _status_error(int(getattr(response, "status", 0)), "bing")
|
|
@@ -223,12 +231,15 @@ def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict
|
|
|
223
231
|
endpoint = _endpoint(args.get("braveEndpoint"), DEFAULT_BRAVE_ENDPOINT, "braveEndpoint")
|
|
224
232
|
from scrapling.fetchers import Fetcher
|
|
225
233
|
|
|
234
|
+
# Brave 的 `count` 上限是 20(文档口径)。传更大的值不会报错,只会被上游截断,
|
|
235
|
+
# 回执里少掉的那几条看不出原因 —— 这里夹到上限,超出的部分由调用方自己翻页。
|
|
226
236
|
try:
|
|
227
237
|
response = Fetcher.get(
|
|
228
238
|
endpoint,
|
|
229
|
-
params={"q": query, "count": limit},
|
|
239
|
+
params={"q": query, "count": min(limit, BRAVE_MAX_COUNT)},
|
|
230
240
|
headers={"X-Subscription-Token": key, "Accept": "application/json"},
|
|
231
241
|
timeout=timeout,
|
|
242
|
+
retries=SEARCH_RETRIES,
|
|
232
243
|
)
|
|
233
244
|
except Exception as error: # noqa: BLE001
|
|
234
245
|
raise _translate(error, "brave") from None
|
|
@@ -257,6 +268,7 @@ def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
|
|
|
257
268
|
json={"q": query, "num": limit},
|
|
258
269
|
headers={"X-API-KEY": key, "Content-Type": "application/json"},
|
|
259
270
|
timeout=timeout,
|
|
271
|
+
retries=SEARCH_RETRIES,
|
|
260
272
|
)
|
|
261
273
|
except Exception as error: # noqa: BLE001
|
|
262
274
|
raise _translate(error, "serper") from None
|
|
@@ -298,7 +310,7 @@ def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) ->
|
|
|
298
310
|
from scrapling.fetchers import Fetcher
|
|
299
311
|
|
|
300
312
|
try:
|
|
301
|
-
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout)
|
|
313
|
+
response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout, retries=SEARCH_RETRIES)
|
|
302
314
|
except Exception as error: # noqa: BLE001
|
|
303
315
|
raise _translate(error, "duckduckgo") from None
|
|
304
316
|
failed = _status_error(int(getattr(response, "status", 0)), "duckduckgo")
|
|
@@ -344,7 +356,7 @@ def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> di
|
|
|
344
356
|
from scrapling.fetchers import Fetcher
|
|
345
357
|
|
|
346
358
|
try:
|
|
347
|
-
response = Fetcher.get(url, params={"q": query, "format": "json"}, timeout=timeout)
|
|
359
|
+
response = Fetcher.get(url, params={"q": query, "format": "json"}, timeout=timeout, retries=SEARCH_RETRIES)
|
|
348
360
|
except Exception as error: # noqa: BLE001
|
|
349
361
|
raise _translate(error, "searxng") from None
|
|
350
362
|
failed = _status_error(int(getattr(response, "status", 0)), "searxng")
|
package/py/session_page.py
CHANGED
|
@@ -11,6 +11,9 @@ def _adapter_error(code: str, message: str, *, details: dict[str, Any] | None =
|
|
|
11
11
|
return AdapterError(code, message, details=details)
|
|
12
12
|
|
|
13
13
|
|
|
14
|
+
# 单条 `wait_time` 的上限:默认动作超时在 30s 量级,无上界会把 page pool 的槽位占死。
|
|
15
|
+
_MAX_WAIT_MS = 60_000
|
|
16
|
+
|
|
14
17
|
_ACTION_TYPES = frozenset(
|
|
15
18
|
{
|
|
16
19
|
"click",
|
|
@@ -53,6 +56,48 @@ def _finish_page(pool: Any, page_info: Any) -> None:
|
|
|
53
56
|
page_info.mark_ready()
|
|
54
57
|
|
|
55
58
|
|
|
59
|
+
def _closed_page_error() -> Exception:
|
|
60
|
+
"""页已被关闭时的错误码。
|
|
61
|
+
|
|
62
|
+
与「页被别的请求占着」分开:`PAGE_BUSY` 的文案是「retry shortly」,而这一页紧接着就会被
|
|
63
|
+
`_finish_page` 从池里摘掉,重试拿到的是 `NO_CURRENT_PAGE` —— 让模型按「稍后重试」去等一个
|
|
64
|
+
已经不存在的页,是把它往错的方向支。`PAGE_CLOSED` 的意思是「这一页没了,重新开一次会话或
|
|
65
|
+
再抓一次」,那才是它该做的事。
|
|
66
|
+
"""
|
|
67
|
+
return _adapter_error("PAGE_CLOSED", "the session's page has been closed; open the session again")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _page_identity(page: Any) -> tuple[str, str]:
|
|
71
|
+
"""读终页的 url 与标题,读不到就给空串。
|
|
72
|
+
|
|
73
|
+
这两个是**纯展示**字段,而 `title()` 是一次远端调用:最后一条动作如果是关窗(点击
|
|
74
|
+
`window.close()`)或页面崩溃,这里会抛 Playwright 的 TargetClosedError。那样整批动作的
|
|
75
|
+
成果(`completed` 计数)会连同这一句一起丢掉,宿主只能看到内部异常 —— 动作其实全做成了。
|
|
76
|
+
所以两项各自兜底,读不出就是空串,由调用方决定怎么措辞。
|
|
77
|
+
"""
|
|
78
|
+
url = ""
|
|
79
|
+
title = ""
|
|
80
|
+
try:
|
|
81
|
+
url = str(page.url)
|
|
82
|
+
except Exception: # noqa: BLE001 —— 纯展示字段,读不到就是空串
|
|
83
|
+
url = ""
|
|
84
|
+
try:
|
|
85
|
+
title = str(page.title())
|
|
86
|
+
except Exception: # noqa: BLE001 —— 同上;`title()` 是远端调用,页一崩就抛
|
|
87
|
+
title = ""
|
|
88
|
+
return url, title
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _number(value: Any) -> bool:
|
|
92
|
+
"""是不是一个真数字:`bool` 是 `int` 的子类,`True` 会被 `float()` 静默变成 1.0。
|
|
93
|
+
|
|
94
|
+
坐标与滚轮位移用这一条判据。传 `true` / `false` 是调用方明显的传参错误,静默成 1.0 / 0.0
|
|
95
|
+
等于替它做了一次带副作用的鼠标位移。同文件对 `wait_time.ms` 早已显式排除 `bool`
|
|
96
|
+
(`isinstance(ms, bool)`),两处判据现在同源。
|
|
97
|
+
"""
|
|
98
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
99
|
+
|
|
100
|
+
|
|
56
101
|
def read_current_page(
|
|
57
102
|
session: Any,
|
|
58
103
|
*,
|
|
@@ -74,11 +119,13 @@ def read_current_page(
|
|
|
74
119
|
page = page_info.page
|
|
75
120
|
try:
|
|
76
121
|
if page.is_closed():
|
|
77
|
-
raise
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
122
|
+
raise _closed_page_error()
|
|
123
|
+
try:
|
|
124
|
+
html = page.content()
|
|
125
|
+
except Exception as error: # 读到一半页被关掉/崩溃,归成「这一页没了」
|
|
126
|
+
raise _closed_page_error() from error
|
|
127
|
+
url, title = _page_identity(page)
|
|
128
|
+
response = _fake_response(str(html), url, 200)
|
|
82
129
|
payload = to_payload(
|
|
83
130
|
response,
|
|
84
131
|
extraction_type=extraction_type,
|
|
@@ -107,6 +154,18 @@ def _require_selector(action: dict[str, Any], kind: str) -> str:
|
|
|
107
154
|
return target
|
|
108
155
|
|
|
109
156
|
|
|
157
|
+
def _has_target(action: dict[str, Any]) -> bool:
|
|
158
|
+
"""动作里是否带了一个**可用**的 target 选择器:非字符串与空串都算没有。
|
|
159
|
+
|
|
160
|
+
校验侧与执行侧必须走同一条判据。分头判会错位:校验侧认可「空串 target + x/y 坐标」这种
|
|
161
|
+
合法写法(坐标位移),而执行侧只判 `isinstance(target, str)` —— 空串是 str,于是它跳过
|
|
162
|
+
坐标分支、落到 `_require_selector` 抛 ACTION_INVALID,再被批次包装成 ACTION_FAILED。
|
|
163
|
+
用户看到的是「执行失败」,真实原因是「这个动作本来就不该带 target」,错误码与下标语义全错位。
|
|
164
|
+
"""
|
|
165
|
+
target = action.get("target")
|
|
166
|
+
return isinstance(target, str) and bool(target)
|
|
167
|
+
|
|
168
|
+
|
|
110
169
|
def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> Any:
|
|
111
170
|
"""执行一个已校验的动作;dialog 注册的处理器会返回,由调用方在批次结束时摘掉。"""
|
|
112
171
|
kind = str(action["type"])
|
|
@@ -132,13 +191,12 @@ def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> Any:
|
|
|
132
191
|
return handler
|
|
133
192
|
if kind == "press_key":
|
|
134
193
|
key = str(action.get("key", ""))
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
page.locator(target).press(key, timeout=timeout_ms)
|
|
194
|
+
if _has_target(action):
|
|
195
|
+
page.locator(_require_selector(action, kind)).press(key, timeout=timeout_ms)
|
|
138
196
|
else:
|
|
139
197
|
page.keyboard.press(key)
|
|
140
198
|
return None
|
|
141
|
-
if kind == "move" and not
|
|
199
|
+
if kind == "move" and not _has_target(action):
|
|
142
200
|
page.mouse.move(float(action["x"]), float(action["y"]))
|
|
143
201
|
return None
|
|
144
202
|
|
|
@@ -184,21 +242,23 @@ def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
|
|
|
184
242
|
if kind in _SELECTOR_ACTIONS:
|
|
185
243
|
_require_selector(action, str(kind))
|
|
186
244
|
if kind == "move":
|
|
187
|
-
target
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
has_target = isinstance(target, str) and bool(target)
|
|
191
|
-
has_point = isinstance(action.get("x"), (int, float)) and isinstance(action.get("y"), (int, float))
|
|
192
|
-
if not has_target and not has_point:
|
|
245
|
+
# 与执行侧同一条判据(`_has_target`):空串 target 不算 target。
|
|
246
|
+
has_point = _number(action.get("x")) and _number(action.get("y"))
|
|
247
|
+
if not _has_target(action) and not has_point:
|
|
193
248
|
raise _adapter_error("ACTION_INVALID", "move needs a non-empty target selector or x/y coordinates")
|
|
194
|
-
if kind == "wheel" and (
|
|
195
|
-
not isinstance(action.get("deltaX"), (int, float)) or not isinstance(action.get("deltaY"), (int, float))
|
|
196
|
-
):
|
|
249
|
+
if kind == "wheel" and (not _number(action.get("deltaX")) or not _number(action.get("deltaY"))):
|
|
197
250
|
raise _adapter_error("ACTION_INVALID", "wheel needs numeric deltaX and deltaY")
|
|
198
251
|
if kind == "wait_time":
|
|
199
252
|
ms = action.get("ms")
|
|
200
253
|
if not isinstance(ms, int) or isinstance(ms, bool) or ms < 0:
|
|
201
254
|
raise _adapter_error("ACTION_INVALID", "wait_time needs a non-negative ms")
|
|
255
|
+
# 上界:默认动作超时是 30s 量级,而单条 wait_time 无上界时模型可以要几个小时,
|
|
256
|
+
# 把整批动作连同共享 page pool 的槽位一起占死。
|
|
257
|
+
if ms > _MAX_WAIT_MS:
|
|
258
|
+
raise _adapter_error(
|
|
259
|
+
"ACTION_INVALID",
|
|
260
|
+
f"wait_time must be at most {_MAX_WAIT_MS} ms",
|
|
261
|
+
)
|
|
202
262
|
if kind == "wait_element":
|
|
203
263
|
state = action.get("state", "visible")
|
|
204
264
|
if not isinstance(state, str) or state not in _ELEMENT_STATES:
|
|
@@ -220,6 +280,20 @@ def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
|
|
|
220
280
|
return actions
|
|
221
281
|
|
|
222
282
|
|
|
283
|
+
def _release_or_error(page: Any, handler: Any) -> Exception | None:
|
|
284
|
+
"""摘一个 dialog 处理器;失败时把异常交回调用方,而不是当场中断收尾。
|
|
285
|
+
|
|
286
|
+
@param page - 当前页
|
|
287
|
+
@param handler - 之前挂上的 dialog 处理器
|
|
288
|
+
@returns 失败时的异常,成功时为 None
|
|
289
|
+
"""
|
|
290
|
+
try:
|
|
291
|
+
_release_dialog_handler(page, handler)
|
|
292
|
+
except Exception as error: # noqa: BLE001 —— 交给调用方在收尾之后统一报
|
|
293
|
+
return error
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
|
|
223
297
|
def _release_dialog_handler(page: Any, handler: Any) -> None:
|
|
224
298
|
"""摘掉一个 dialog 处理器;页已关闭时不必再碰它(处理器随页一起消失)。"""
|
|
225
299
|
if page.is_closed():
|
|
@@ -243,7 +317,7 @@ def run_actions(
|
|
|
243
317
|
dialog_handlers: list[Any] = []
|
|
244
318
|
try:
|
|
245
319
|
if page.is_closed():
|
|
246
|
-
raise
|
|
320
|
+
raise _closed_page_error()
|
|
247
321
|
for index, action in enumerate(prepared, start=1):
|
|
248
322
|
try:
|
|
249
323
|
handler = _perform(page, action, timeout_ms)
|
|
@@ -260,14 +334,23 @@ def run_actions(
|
|
|
260
334
|
f"action {index} ({action['type']}) failed: {type(error).__name__}: {error}",
|
|
261
335
|
details={"actionIndex": index},
|
|
262
336
|
) from error
|
|
337
|
+
# 终页信息在 finally 之外读:动作全做成了才走这里,而这两项各自兜底(一次关窗或页崩溃
|
|
338
|
+
# 不该把已经完成的批次报成内部异常)。
|
|
339
|
+
url, title = _page_identity(page)
|
|
263
340
|
return {
|
|
264
341
|
"completed": completed,
|
|
265
|
-
"finalUrl":
|
|
266
|
-
"title":
|
|
342
|
+
"finalUrl": url,
|
|
343
|
+
"title": title,
|
|
267
344
|
}
|
|
268
345
|
finally:
|
|
269
346
|
# 页面在共享的 page pool 里跨请求复用:批次一结束就摘掉 dialog 处理器,
|
|
270
347
|
# 否则后续请求弹出的对话框会被这一次动作留下的处理器替用户应答。
|
|
271
|
-
|
|
272
|
-
|
|
348
|
+
# 摘处理器失败不能挡住 _finish_page:那一句才是把页还给池子的那一步,
|
|
349
|
+
# 少了它页面永久 PAGE_BUSY、后续请求全被拒。所以先逐条摘并收集失败,
|
|
350
|
+
# 让收尾先跑完,再把失败一次性说出去 —— 不静默吞,也不 try/except/continue。
|
|
351
|
+
release_failures = [_release_or_error(page, handler) for handler in dialog_handlers]
|
|
273
352
|
_finish_page(session.page_pool, page_info)
|
|
353
|
+
# 收尾跑完之后再一次性上报:失败有可读出口,但不会挡住把页还给池子。
|
|
354
|
+
first_failure = next((item for item in release_failures if item is not None), None)
|
|
355
|
+
if first_failure is not None:
|
|
356
|
+
raise first_failure
|