-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplaywright_backend.py
More file actions
353 lines (309 loc) · 12.2 KB
/
playwright_backend.py
File metadata and controls
353 lines (309 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""
Playwright backend implementation for BrowserBackend protocol.
This wraps existing SentienceBrowser/AsyncSentienceBrowser to provide
a unified interface, enabling code that works with both browser-use
(CDPBackendV0) and native Playwright (PlaywrightBackend).
Usage:
from sentience import SentienceBrowserAsync
from sentience.backends import PlaywrightBackend, snapshot_from_backend
browser = SentienceBrowserAsync()
await browser.start()
await browser.goto("https://example.com")
# Create backend from existing browser
backend = PlaywrightBackend(browser.page)
# Use backend-agnostic functions
snap = await snapshot_from_backend(backend)
await click(backend, element.bbox)
"""
import asyncio
import inspect
import mimetypes
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from ..models import TabInfo
from .protocol import BrowserBackend, LayoutMetrics, ViewportInfo
if TYPE_CHECKING:
from playwright.async_api import Page as AsyncPage
class PlaywrightBackend:
"""
Playwright-based implementation of BrowserBackend.
Wraps a Playwright async Page to provide the standard backend interface.
This enables using backend-agnostic actions with existing SentienceBrowser code.
"""
def __init__(self, page: "AsyncPage") -> None:
"""
Initialize Playwright backend.
Args:
page: Playwright async Page object
"""
self._page = page
self._cached_viewport: ViewportInfo | None = None
self._downloads: list[dict[str, Any]] = []
self._tab_registry: dict[str, "AsyncPage"] = {}
# Best-effort download tracking (does not change behavior unless a download occurs).
# pylint: disable=broad-exception-caught
try:
result = self._page.on(
"download", lambda d: asyncio.create_task(self._track_download(d))
)
if inspect.isawaitable(result):
try:
asyncio.get_running_loop().create_task(result)
except RuntimeError:
pass
except Exception:
pass
@property
def downloads(self) -> list[dict[str, Any]]:
"""Best-effort Playwright download records."""
return self._downloads
async def _track_download(self, download: Any) -> None:
rec: dict[str, Any] = {
"status": "started",
"suggested_filename": getattr(download, "suggested_filename", None),
"url": getattr(download, "url", None),
}
self._downloads.append(rec)
try:
# Wait for completion and capture path if Playwright provides it.
p = await download.path()
if p:
rec["status"] = "completed"
rec["path"] = str(p)
rec["filename"] = Path(str(p)).name
try:
rec["size_bytes"] = int(os.path.getsize(str(p)))
except Exception:
pass
try:
mt, _enc = mimetypes.guess_type(str(p))
if mt:
rec["mime_type"] = mt
except Exception:
pass
else:
rec["status"] = "completed"
except Exception as e:
rec["status"] = "failed"
rec["error"] = str(e)
@property
def page(self) -> "AsyncPage":
"""Access the underlying Playwright page."""
return self._page
async def list_tabs(self) -> list[TabInfo]:
self._prune_tabs()
context = self._page.context
tabs: list[TabInfo] = []
for page in context.pages:
tab_id = self._ensure_tab_id(page)
title = None
try:
title = await page.title()
except Exception: # pylint: disable=broad-exception-caught
title = None
tabs.append(
TabInfo(
tab_id=tab_id,
url=getattr(page, "url", None),
title=title,
is_active=page == self._page,
)
)
return tabs
async def open_tab(self, url: str) -> TabInfo:
self._prune_tabs()
context = self._page.context
page = await context.new_page()
await page.goto(url)
self._page = page
tab_id = self._ensure_tab_id(page)
title = None
try:
title = await page.title()
except Exception: # pylint: disable=broad-exception-caught
title = None
return TabInfo(tab_id=tab_id, url=getattr(page, "url", None), title=title, is_active=True)
async def switch_tab(self, tab_id: str) -> TabInfo:
self._prune_tabs()
page = self._tab_registry.get(tab_id)
if page is None:
raise ValueError(f"unknown tab_id: {tab_id}")
self._page = page
try:
await page.bring_to_front()
except Exception: # pylint: disable=broad-exception-caught
pass
title = None
try:
title = await page.title()
except Exception: # pylint: disable=broad-exception-caught
title = None
return TabInfo(tab_id=tab_id, url=getattr(page, "url", None), title=title, is_active=True)
async def close_tab(self, tab_id: str) -> TabInfo:
self._prune_tabs()
page = self._tab_registry.get(tab_id)
if page is None:
raise ValueError(f"unknown tab_id: {tab_id}")
info = TabInfo(
tab_id=tab_id,
url=getattr(page, "url", None),
title=None,
is_active=page == self._page,
)
try:
info.title = await page.title()
except Exception: # pylint: disable=broad-exception-caught
info.title = None
await page.close()
self._tab_registry.pop(tab_id, None)
if self._page == page:
context = page.context
pages = context.pages
if pages:
self._page = pages[0]
return info
def _ensure_tab_id(self, page: "AsyncPage") -> str:
self._prune_tabs()
for tab_id, entry in self._tab_registry.items():
if entry == page:
return tab_id
tab_id = f"tab-{id(page)}"
self._tab_registry[tab_id] = page
return tab_id
def _prune_tabs(self) -> None:
dead: list[str] = []
for tab_id, page in self._tab_registry.items():
is_closed = getattr(page, "is_closed", None)
try:
closed = is_closed() if callable(is_closed) else bool(is_closed)
except Exception: # pragma: no cover - defensive
closed = False
if closed:
dead.append(tab_id)
for tab_id in dead:
self._tab_registry.pop(tab_id, None)
async def refresh_page_info(self) -> ViewportInfo:
"""Cache viewport + scroll offsets; cheap & safe to call often."""
result = await self._page.evaluate(
"""
(() => ({
width: window.innerWidth,
height: window.innerHeight,
scroll_x: window.scrollX,
scroll_y: window.scrollY,
content_width: document.documentElement.scrollWidth,
content_height: document.documentElement.scrollHeight
}))()
"""
)
self._cached_viewport = ViewportInfo(
width=result.get("width", 0),
height=result.get("height", 0),
scroll_x=result.get("scroll_x", 0),
scroll_y=result.get("scroll_y", 0),
content_width=result.get("content_width"),
content_height=result.get("content_height"),
)
return self._cached_viewport
async def eval(self, expression: str) -> Any:
"""Evaluate JavaScript expression in page context."""
return await self._page.evaluate(expression)
async def call(
self,
function_declaration: str,
args: list[Any] | None = None,
) -> Any:
"""Call JavaScript function with arguments."""
if args:
return await self._page.evaluate(function_declaration, *args)
return await self._page.evaluate(f"({function_declaration})()")
async def get_layout_metrics(self) -> LayoutMetrics:
"""Get page layout metrics."""
# Playwright doesn't expose CDP directly in the same way,
# so we approximate using JavaScript
result = await self._page.evaluate(
"""
(() => ({
viewport_x: window.scrollX,
viewport_y: window.scrollY,
viewport_width: window.innerWidth,
viewport_height: window.innerHeight,
content_width: document.documentElement.scrollWidth,
content_height: document.documentElement.scrollHeight,
device_scale_factor: window.devicePixelRatio || 1
}))()
"""
)
return LayoutMetrics(
viewport_x=result.get("viewport_x", 0),
viewport_y=result.get("viewport_y", 0),
viewport_width=result.get("viewport_width", 0),
viewport_height=result.get("viewport_height", 0),
content_width=result.get("content_width", 0),
content_height=result.get("content_height", 0),
device_scale_factor=result.get("device_scale_factor", 1.0),
)
async def screenshot_png(self) -> bytes:
"""Capture viewport screenshot as PNG bytes."""
return await self._page.screenshot(type="png")
async def screenshot_jpeg(self, quality: int | None = None) -> bytes:
"""Capture viewport screenshot as JPEG bytes."""
q = 80 if quality is None else max(1, min(int(quality), 100))
return await self._page.screenshot(type="jpeg", quality=q)
async def mouse_move(self, x: float, y: float) -> None:
"""Move mouse to viewport coordinates."""
await self._page.mouse.move(x, y)
async def mouse_click(
self,
x: float,
y: float,
button: Literal["left", "right", "middle"] = "left",
click_count: int = 1,
) -> None:
"""Click at viewport coordinates."""
await self._page.mouse.click(x, y, button=button, click_count=click_count)
async def wheel(
self,
delta_y: float,
x: float | None = None,
y: float | None = None,
) -> None:
"""Scroll using mouse wheel."""
# Get viewport center if coordinates not provided
if x is None or y is None:
if self._cached_viewport is None:
await self.refresh_page_info()
assert self._cached_viewport is not None
x = x if x is not None else self._cached_viewport.width / 2
y = y if y is not None else self._cached_viewport.height / 2
await self._page.mouse.wheel(0, delta_y)
async def type_text(self, text: str, delay_ms: float | None = None) -> None:
"""Type text using keyboard input."""
delay = 0 if delay_ms is None else max(0, float(delay_ms))
await self._page.keyboard.type(text, delay=delay)
async def wait_ready_state(
self,
state: Literal["interactive", "complete"] = "interactive",
timeout_ms: int = 15000,
) -> None:
"""Wait for document.readyState to reach target state."""
acceptable_states = {"complete"} if state == "complete" else {"interactive", "complete"}
start = time.monotonic()
timeout_sec = timeout_ms / 1000.0
while True:
elapsed = time.monotonic() - start
if elapsed >= timeout_sec:
raise TimeoutError(
f"Timed out waiting for document.readyState='{state}' " f"after {timeout_ms}ms"
)
current_state = await self._page.evaluate("document.readyState")
if current_state in acceptable_states:
return
await asyncio.sleep(0.1)
async def get_url(self) -> str:
"""Get current page URL."""
return self._page.url
# Verify protocol compliance at import time
assert isinstance(PlaywrightBackend.__new__(PlaywrightBackend), BrowserBackend)