`Page.on` method doesn't accept async handlers
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()
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?
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.
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~~
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 No need, the PR was merged and made it into the 0.170 release