Update playwright/README.md

This commit is contained in:
2024-12-24 06:47:59 +00:00
parent 8ef1bdb65b
commit 212bbdf2f5

View File

@@ -5,33 +5,34 @@ Linux (WSL Debian)
pip install playwright pip install playwright
playwright install --with-deps playwright install --with-deps
""" """
# %% def Page():
def sync(coro): def sync(func):
import asyncio, functools if not hasattr(sync, 'call'):
if not asyncio.iscoroutinefunction(coro): return coro sync.call = __import__('queue').Queue()
@functools.wraps(coro) def server():
def wrapper(*args, **kwargs): while sync.call.get():
loop, future = asyncio.get_event_loop(), asyncio.ensure_future(coro(*args, **kwargs)) func, args, kwargs = sync.obj
while not future.done(): sync.obj = func(*args, **kwargs)
loop._process_events(loop._selector.select(0)) sync.call.task_done()
if (ready := loop._ready) and (handle := ready.popleft())._cancelled is False: __import__('asyncio').set_event_loop_policy(None)
task = (tasks := asyncio.tasks._current_tasks).pop(loop, None) __import__('threading').Thread(target=server).start()
handle._run(); tasks[loop] = task @__import__('functools').wraps(func)
return future.result() def wrapper(*args, **kwargs):
return wrapper sync.obj = func, args, kwargs
sync.call.put(True); sync.call.join()
@sync return sync.obj
async def Page(headless=True): return wrapper
from playwright.async_api import async_playwright @sync
browser = await (await async_playwright().start()).firefox.launch(headless=headless) def Page():
(page := await browser.new_page()).set_default_timeout(0) from playwright.sync_api import sync_playwright
for attr in dir(page): browser = sync_playwright().start().firefox.launch()
if callable(method := getattr(page, attr)): setattr(page, attr, sync(method)) (context := browser.new_context()).set_default_timeout(0)
try: for attr in dir(page := context.new_page()):
from IPython.display import Image if attr[0] != '_' and callable(method := getattr(page, attr)):
page.goto = lambda url, goto=page.goto: goto(url) and Image(page.screenshot()) setattr(page, attr, sync(method))
finally: page._repr_png_ = page.screenshot
return page return page
return Page()
(page := Page()).goto('https://example.org') (page := Page()).goto('https://example.org')
print(page.title()) # Example Domain print(page.title()) # Example Domain
``` ```