Update playwright/README.md
This commit is contained in:
@@ -6,28 +6,32 @@ pip install playwright
|
||||
playwright install --with-deps
|
||||
"""
|
||||
# %%
|
||||
import asyncio, functools
|
||||
def _run_once(loop):
|
||||
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
|
||||
(loop := asyncio.get_event_loop()).__class__._run_once = _run_once
|
||||
asyncio.run = loop.run_until_complete; loop.__class__._check_running = lambda _: None
|
||||
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 := lambda coro: functools.wraps(coro)(
|
||||
lambda *args, **kwargs: asyncio.run(coro(*args, **kwargs))))
|
||||
@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 asyncio.iscoroutinefunction(method := getattr(page, attr)):
|
||||
setattr(page, attr, sync(method))
|
||||
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
|
||||
finally:
|
||||
return page
|
||||
(page := Page()).goto('https://example.org')
|
||||
print(page.title()) # Example Domain
|
||||
```
|
||||
Reference in New Issue
Block a user