@jayyuen66/dsh-scrapling 0.1.5 → 0.1.7

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.
@@ -12,7 +12,7 @@
12
12
  from __future__ import annotations
13
13
 
14
14
  from functools import lru_cache
15
- from threading import RLock
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
- port = f":{parts.port}" if parts.port is not None else ""
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
- try:
44
- from redis import Redis
45
- except ModuleNotFoundError as error:
46
- # 没装客户端是**部署**的问题,不是抓取失败:点名的错误让人知道该装 adaptive-redis 包。
47
- raise RedisUnavailable(
48
- "the redis client is missing; install the adaptive-redis pack (pip install redis)"
49
- ) from error
50
- # 超时要真的交给客户端:早先它只落在 self.timeout_seconds 上、全文件没有使用点,于是
51
- # socket 超时一直是客户端自己的默认值(连接卡住时表现为整场抓取挂死)。
52
- return Redis.from_url(
53
- redis_url,
54
- decode_responses=True,
55
- socket_timeout=timeout_seconds,
56
- socket_connect_timeout=timeout_seconds,
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._lock = RLock()
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
- with self._lock:
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
- with self._lock:
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
- with self._lock:
127
- close = getattr(self._client, "close", None)
128
- if callable(close):
129
- close()
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
- parts = urlparse(href if "://" in href else f"https:{href}" if href.startswith("//") else href)
282
- if "duckduckgo.com" in parts.netloc and parts.path.startswith("/l/"):
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]
@@ -107,22 +107,29 @@ def _require_selector(action: dict[str, Any], kind: str) -> str:
107
107
  return target
108
108
 
109
109
 
110
- def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> None:
111
- """执行一个已校验的动作。"""
110
+ def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> Any:
111
+ """执行一个已校验的动作;dialog 注册的处理器会返回,由调用方在批次结束时摘掉。"""
112
112
  kind = str(action["type"])
113
113
  if kind == "wait_time":
114
114
  page.wait_for_timeout(int(action["ms"]))
115
- return
115
+ return None
116
116
  if kind == "wait_load":
117
117
  page.wait_for_load_state(str(action.get("state", "load")), timeout=timeout_ms)
118
- return
118
+ return None
119
119
  if kind == "wheel":
120
120
  page.mouse.wheel(float(action["deltaX"]), float(action["deltaY"]))
121
- return
121
+ return None
122
122
  if kind == "dialog":
123
123
  accept = action.get("accept", True) is not False
124
- page.once("dialog", lambda dialog: dialog.accept() if accept else dialog.dismiss())
125
- return
124
+
125
+ def handler(dialog: Any) -> None:
126
+ if accept:
127
+ dialog.accept()
128
+ else:
129
+ dialog.dismiss()
130
+
131
+ page.once("dialog", handler)
132
+ return handler
126
133
  if kind == "press_key":
127
134
  key = str(action.get("key", ""))
128
135
  target = action.get("target")
@@ -130,10 +137,10 @@ def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> None:
130
137
  page.locator(target).press(key, timeout=timeout_ms)
131
138
  else:
132
139
  page.keyboard.press(key)
133
- return
140
+ return None
134
141
  if kind == "move" and not isinstance(action.get("target"), str):
135
142
  page.mouse.move(float(action["x"]), float(action["y"]))
136
- return
143
+ return None
137
144
 
138
145
  selector = _require_selector(action, kind)
139
146
  locator = page.locator(selector)
@@ -156,6 +163,7 @@ def _perform(page: Any, action: dict[str, Any], timeout_ms: int) -> None:
156
163
  locator.wait_for(state=str(action.get("state", "visible")), timeout=timeout_ms)
157
164
  else: # pragma: no cover —— 类型白名单已挡住
158
165
  raise _adapter_error("ACTION_INVALID", f"unknown action type: {kind}")
166
+ return None
159
167
 
160
168
 
161
169
  def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
@@ -168,17 +176,21 @@ def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
168
176
  if not isinstance(item, dict):
169
177
  raise _adapter_error("ACTION_INVALID", f"action {index} must be an object")
170
178
  kind = item.get("type")
171
- if kind not in _ACTION_TYPES:
179
+ # frozenset 的成员判断先哈希:type 写成 list/dict 会抛 TypeError 而不是 ACTION_INVALID,
180
+ # 宿主看到的就是内部异常。非字符串与未知类型在这里走同一条判据。
181
+ if not isinstance(kind, str) or kind not in _ACTION_TYPES:
172
182
  raise _adapter_error("ACTION_INVALID", f"action {index} has an unknown type: {kind!r}")
173
183
  action = dict(item)
174
184
  if kind in _SELECTOR_ACTIONS:
175
185
  _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")
186
+ if kind == "move":
187
+ target = action.get("target")
188
+ # 空串 target 不算 target:_perform 会把它当「有 target」交给 locator,
189
+ # 执行期再抛 ACTION_INVALID 又被包装成 ACTION_FAILED,错误码与下标语义都错位。
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:
193
+ raise _adapter_error("ACTION_INVALID", "move needs a non-empty target selector or x/y coordinates")
182
194
  if kind == "wheel" and (
183
195
  not isinstance(action.get("deltaX"), (int, float)) or not isinstance(action.get("deltaY"), (int, float))
184
196
  ):
@@ -189,20 +201,32 @@ def _validate_actions(value: Any, max_actions: int) -> list[dict[str, Any]]:
189
201
  raise _adapter_error("ACTION_INVALID", "wait_time needs a non-negative ms")
190
202
  if kind == "wait_element":
191
203
  state = action.get("state", "visible")
192
- if state not in _ELEMENT_STATES:
204
+ if not isinstance(state, str) or state not in _ELEMENT_STATES:
193
205
  raise _adapter_error("ACTION_INVALID", f"unknown element state: {state!r}")
194
206
  if kind == "wait_load":
195
207
  state = action.get("state", "load")
196
- if state not in _LOAD_STATES:
208
+ if not isinstance(state, str) or state not in _LOAD_STATES:
197
209
  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")
210
+ if kind == "press_key":
211
+ key = action.get("key")
212
+ # 空字符串 key 能过 isinstance,执行期才由 Playwright 抛错并被包装成 ACTION_FAILED。
213
+ if not isinstance(key, str) or not key:
214
+ raise _adapter_error("ACTION_INVALID", "press_key needs a non-empty key")
215
+ if kind == "checkbox" and not isinstance(action.get("checked", True), bool):
216
+ raise _adapter_error("ACTION_INVALID", "checkbox checked must be a boolean")
200
217
  if kind == "dialog" and not isinstance(action.get("accept", True), bool):
201
218
  raise _adapter_error("ACTION_INVALID", "dialog accept must be a boolean")
202
219
  actions.append(action)
203
220
  return actions
204
221
 
205
222
 
223
+ def _release_dialog_handler(page: Any, handler: Any) -> None:
224
+ """摘掉一个 dialog 处理器;页已关闭时不必再碰它(处理器随页一起消失)。"""
225
+ if page.is_closed():
226
+ return
227
+ page.remove_listener("dialog", handler)
228
+
229
+
206
230
  def run_actions(
207
231
  session: Any,
208
232
  *,
@@ -216,25 +240,34 @@ def run_actions(
216
240
  page_info = _ready_page(session)
217
241
  page = page_info.page
218
242
  completed = 0
243
+ dialog_handlers: list[Any] = []
219
244
  try:
220
245
  if page.is_closed():
221
246
  raise _adapter_error("PAGE_BUSY", "the session's page has been closed")
222
247
  for index, action in enumerate(prepared, start=1):
223
248
  try:
224
- _perform(page, action, timeout_ms)
249
+ handler = _perform(page, action, timeout_ms)
250
+ if handler is not None:
251
+ dialog_handlers.append(handler)
252
+ completed = index
253
+ if slowly:
254
+ page.wait_for_timeout(100)
225
255
  except Exception as error:
256
+ # 慢速间隔也在这一层里:页在动作之间被关掉时同样按 ACTION_FAILED 点名下标,
257
+ # 而不是把裸异常漏给宿主。
226
258
  raise _adapter_error(
227
259
  "ACTION_FAILED",
228
260
  f"action {index} ({action['type']}) failed: {type(error).__name__}: {error}",
229
261
  details={"actionIndex": index},
230
262
  ) from error
231
- completed = index
232
- if slowly:
233
- page.wait_for_timeout(100)
234
263
  return {
235
264
  "completed": completed,
236
265
  "finalUrl": str(page.url),
237
266
  "title": str(page.title()),
238
267
  }
239
268
  finally:
269
+ # 页面在共享的 page pool 里跨请求复用:批次一结束就摘掉 dialog 处理器,
270
+ # 否则后续请求弹出的对话框会被这一次动作留下的处理器替用户应答。
271
+ for handler in dialog_handlers:
272
+ _release_dialog_handler(page, handler)
240
273
  _finish_page(session.page_pool, page_info)