0
v-firecrawl/apps/playwright-service/main.py

76 lines
2.1 KiB
Python
Raw Normal View History

2024-04-25 13:31:28 -04:00
from fastapi import FastAPI
from playwright.async_api import async_playwright, Browser
2024-04-15 17:01:47 -04:00
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from os import environ
2024-05-31 18:39:54 -04:00
PROXY_SERVER = environ.get("PROXY_SERVER", None)
PROXY_USERNAME = environ.get("PROXY_USERNAME", None)
PROXY_PASSWORD = environ.get("PROXY_PASSWORD", None)
BLOCK_MEDIA = environ.get("BLOCK_MEDIA", "False").upper() == "TRUE"
2024-04-25 13:31:28 -04:00
2024-04-15 17:01:47 -04:00
app = FastAPI()
2024-04-15 17:01:47 -04:00
class UrlModel(BaseModel):
url: str
2024-05-09 21:00:58 -04:00
wait: int = None
2024-05-31 18:39:54 -04:00
wait_until: str = "load"
headers: dict = None
2024-04-15 17:01:47 -04:00
2024-04-25 13:31:28 -04:00
browser: Browser = None
@app.on_event("startup")
async def startup_event():
global browser
playwright = await async_playwright().start()
browser = await playwright.chromium.launch()
2024-04-15 17:01:47 -04:00
2024-04-25 13:31:28 -04:00
@app.on_event("shutdown")
async def shutdown_event():
await browser.close()
2024-04-15 17:01:47 -04:00
2024-04-25 13:31:28 -04:00
@app.post("/html")
async def root(body: UrlModel):
context = None
if PROXY_SERVER and PROXY_USERNAME and PROXY_PASSWORD:
2024-05-31 18:39:54 -04:00
context = await browser.new_context(
proxy={
"server": PROXY_SERVER,
"username": PROXY_USERNAME,
"password": PROXY_PASSWORD,
}
)
else:
context = await browser.new_context()
if BLOCK_MEDIA:
2024-05-31 18:39:54 -04:00
await context.route(
"**/*.{png,jpg,jpeg,gif,svg,mp3,mp4,avi,flac,ogg,wav,webm}",
handler=lambda route, request: route.abort(),
)
2024-04-25 13:31:28 -04:00
page = await context.new_page()
2024-05-31 18:39:54 -04:00
# Set headers if provided
if body.headers:
await page.set_extra_http_headers(body.headers)
await page.goto(
body.url,
2024-05-31 18:39:54 -04:00
timeout=15000,
wait_until=body.wait_until if body.wait_until else "load",
) # Set max timeout to 15s
if body.wait: # Check if wait parameter is provided in the request body
await page.wait_for_timeout(
body.wait
) # Convert seconds to milliseconds for playwright
2024-04-25 13:31:28 -04:00
page_content = await page.content()
await context.close()
json_compatible_item_data = {"content": page_content}
return JSONResponse(content=json_compatible_item_data)