Playwright异步调用时的page on response

Playwright一般用同步的方式调用即可,但某些情况下,比如在FastAPI框架中使用时,就需要用异步的方式。

在这种方式下如果要处理page的response事件,写法就要变一变,不然会报错。

下面是一个完整的示例:

import asyncio
from playwright.async_api import async_playwright

async def request_event_handler(response):
    print("HTTP Status code: {}".format(response.status))
    body = await response.body()
    print("HTML body page: {}".format(body))

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()
        page = await context.new_page()
        page.on(
            "response",
            lambda response: asyncio.create_task(request_event_handler(response)),
        )
        await page.goto("https://m.baidu.com/")
        await page.wait_for_load_state('networkidle')
        await browser.close()

asyncio.get_event_loop().run_until_complete(main())

如果是在FastAPI中引用这段代码就执行main函数,不要用asyncio.get_event_loop().run_until_complete(main()),直接await main()即可,当然路由定义上要加上async

Leave a Comment

豫ICP备19001387号-1