37 lines
1.3 KiB
Markdown
37 lines
1.3 KiB
Markdown
```python
|
|
"""
|
|
Linux (WSL Debian)
|
|
|
|
pip install playwright
|
|
playwright install --with-deps
|
|
"""
|
|
# %%
|
|
def sync(coro):
|
|
import asyncio, functools
|
|
if not asyncio.iscoroutinefunction(coro): return coro
|
|
@functools.wraps(coro)
|
|
def wrapper(*args, **kwargs):
|
|
loop, future = asyncio.get_event_loop(), asyncio.ensure_future(coro(*args, **kwargs))
|
|
while not future.done():
|
|
loop._process_events(loop._selector.select(0))
|
|
if (ready := loop._ready) and (handle := ready.popleft())._cancelled is False:
|
|
task = (tasks := asyncio.tasks._current_tasks).pop(loop, None)
|
|
handle._run(); tasks[loop] = task
|
|
return future.result()
|
|
return wrapper
|
|
|
|
@sync
|
|
async def Page(headless=True):
|
|
from playwright.async_api import async_playwright
|
|
browser = await (await async_playwright().start()).firefox.launch(headless=headless)
|
|
(page := await browser.new_page()).set_default_timeout(0)
|
|
for attr in dir(page):
|
|
if callable(method := getattr(page, attr)): setattr(page, attr, sync(method))
|
|
try:
|
|
from IPython.display import Image
|
|
page.goto = lambda url, goto=page.goto: goto(url) and Image(page.screenshot())
|
|
finally:
|
|
return page
|
|
(page := Page()).goto('https://example.org')
|
|
print(page.title()) # Example Domain
|
|
``` |