Update playwright/README.md
This commit is contained in:
@@ -5,33 +5,34 @@ 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:
|
||||
def Page():
|
||||
def sync(func):
|
||||
if not hasattr(sync, 'call'):
|
||||
sync.call = __import__('queue').Queue()
|
||||
def server():
|
||||
while sync.call.get():
|
||||
func, args, kwargs = sync.obj
|
||||
sync.obj = func(*args, **kwargs)
|
||||
sync.call.task_done()
|
||||
__import__('asyncio').set_event_loop_policy(None)
|
||||
__import__('threading').Thread(target=server).start()
|
||||
@__import__('functools').wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
sync.obj = func, args, kwargs
|
||||
sync.call.put(True); sync.call.join()
|
||||
return sync.obj
|
||||
return wrapper
|
||||
@sync
|
||||
def Page():
|
||||
from playwright.sync_api import sync_playwright
|
||||
browser = sync_playwright().start().firefox.launch()
|
||||
(context := browser.new_context()).set_default_timeout(0)
|
||||
for attr in dir(page := context.new_page()):
|
||||
if attr[0] != '_' and callable(method := getattr(page, attr)):
|
||||
setattr(page, attr, sync(method))
|
||||
page._repr_png_ = page.screenshot
|
||||
return page
|
||||
return Page()
|
||||
(page := Page()).goto('https://example.org')
|
||||
print(page.title()) # Example Domain
|
||||
```
|
||||
Reference in New Issue
Block a user