You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI应用的函数中运行Playwright Asyncio代码?

在FastAPI中集成Playwright异步代码的实现方案

问题描述

我正在用FastAPI和Playwright构建API,不清楚如何将Playwright的异步代码整合到FastAPI的接口函数中。现有两段示例代码:

Playwright异步示例代码

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("http://playwright.dev")
        print(await page.title())
        await browser.close()

asyncio.run(main())

FastAPI示例代码

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/playwright")
def run_playwright():
    return "Results from running Playwright"

需要实现的是在FastAPI的/playwright接口函数内运行Playwright的异步代码。


解决方案

1. 将FastAPI接口改为异步函数

FastAPI原生支持异步端点,只需把接口函数定义改为async def,就能直接在函数内部使用await调用异步操作,无需手动启动新的事件循环。

2. 整合Playwright异步逻辑到接口

直接在异步接口函数内编写Playwright的异步代码逻辑,不需要使用asyncio.run()(FastAPI会自动管理事件循环)。

基础整合代码示例

from fastapi import FastAPI
from playwright.async_api import async_playwright

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/playwright")
async def run_playwright():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("http://playwright.dev")
        page_title = await page.title()
        await browser.close()
    return {"page_title": page_title}

3. 优化:复用浏览器实例(提升性能)

每次请求都启动和关闭浏览器会大幅降低接口性能,建议在应用启动时初始化一个全局浏览器实例,应用关闭时再销毁:

from fastapi import FastAPI
from playwright.async_api import async_playwright, Browser

app = FastAPI()
browser: Browser | None = None

@app.on_event("startup")
async def startup_event():
    global browser
    p = await async_playwright().start()
    browser = await p.chromium.launch()

@app.on_event("shutdown")
async def shutdown_event():
    await browser.close()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/playwright")
async def run_playwright():
    if not browser:
        return {"error": "Browser not initialized"}
    page = await browser.new_page()
    await page.goto("http://playwright.dev")
    page_title = await page.title()
    await page.close()
    return {"page_title": page_title}

注意事项

  • 安装依赖:执行pip install fastapi uvicorn playwright,然后运行playwright install安装所需的浏览器驱动。
  • 无头模式:默认情况下Playwright以无头模式启动浏览器,若需要调试可设置launch(headless=False)。
  • 部署注意:在服务器环境部署时,需确保有足够权限运行浏览器,若遇到问题可参考Playwright官方文档的部署指南。

参考文档

  • FastAPI官方中文文档
  • Playwright Python官方中文文档

内容的提问来源于stack exchange,提问作者MrGuemez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:55:13