playwright-python icon indicating copy to clipboard operation
playwright-python copied to clipboard

`Page.on` method doesn't accept async handlers

Open duyixian1234 opened this issue 6 years ago • 5 comments

I tried to use playwright to download bing's index page's backgroud image with page.on('response', handler), while the handler parameter can't be an async function now. I have to use a strange way like this.

coroutines = []


async def downloadBg(response: Response):
    with open(f"bing-{datetime.now().date()}.jpeg", "wb") as f:
        f.write(await response.body())


def handleResponse(response: Response):
    if response.headers.get("content-type", "unknown") == "image/jpeg":
        coroutines.append(downloadBg(response))

async def run(playwright):
    browser = await playwright.chromium.launch(headless=True)
    context: BrowserContext = await browser.newContext()

    # Open new page
    page: Page = await context.newPage()

    page.on("request", None)
    page.on("response", handleResponse)

    # Go to https://cn.bing.com/
    await page.goto("https://cn.bing.com")

    await asyncio.gather(*coroutines)

    # Close page
    await page.close()

    # ---------------------
    await context.close()
    await browser.close()

duyixian1234 avatar Nov 17 '20 04:11 duyixian1234

Open to doing it, need more details.

So you'd like us to await or schedule the coroutines returned from the event handler? How do you plan to gather them in the end? Could you share the way you'd like your snippet to look?

pavelfeldman avatar Nov 21 '20 18:11 pavelfeldman

We ran into this with pyppeteer. If I'm not mistaken, this is actually super easy to implement. You'll just need to use pyee.AsyncIOEventEmitter instead of pyee.EventEmitter.

Mattwmaster58 avatar Dec 07 '20 20:12 Mattwmaster58

See #353

~~@duyixian1234 Try installing from my repo to see if you can use an async callback function: pip install git+https://github.com/Mattwmaster58/playwright-python.git@asyncio-event-emitter~~

Mattwmaster58 avatar Dec 07 '20 20:12 Mattwmaster58

See #353

@duyixian1234 Try installing from my repo to see if you can use an async callback function: pip install git+https://github.com/Mattwmaster58/playwright-python.git@asyncio-event-emitter

Thanks a lot, and I would like to have a try

duyixian1234 avatar Dec 17 '20 02:12 duyixian1234

@duyixian1234 No need, the PR was merged and made it into the 0.170 release

Mattwmaster58 avatar Dec 17 '20 02:12 Mattwmaster58