Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

Merge branch 'main' into playwright-service-bug-222

Rafael Millerb80fb374e512
diff --cc apps/api/src/scraper/WebScraper/single_url.ts
index 70b4aa67b,911382fbe..a99b36501
--- a/apps/api/src/scraper/WebScraper/single_url.ts
+++ b/apps/api/src/scraper/WebScraper/single_url.ts
@@@ -142,22 -153,16 +153,22 @@@ export async function scrapWithPlaywrig
return "";
}
- const contentType = response.headers['content-type'];
- if (contentType && contentType.includes('application/pdf')) {
+ const contentType = response.headers["content-type"];
+ if (contentType && contentType.includes("application/pdf")) {
return fetchAndProcessPdf(url);
} else {
- const data = await response.json();
- const html = data.content;
- return html ?? "";
+ const textData = await response.text();
+ try {
+ const data = JSON.parse(textData);
+ const html = data.content;
+ return html ?? "";
+ } catch (jsonError) {
+ console.error(`[Playwright] Error parsing JSON response for url: ${url} -> ${jsonError}`);
+ return "";
+ }
}
} catch (error) {
- console.error(`[Playwright][c] Error fetching url: ${url} -> ${error}`);
+ console.error(`[Playwright] Error fetching url: ${url} -> ${error}`);
return "";
}
}
diff --cc apps/playwright-service/main.py
index 3c1ff19e0,b4ac71592..8ef74187c
--- a/apps/playwright-service/main.py
+++ b/apps/playwright-service/main.py
@@@ -1,75 -1,74 +1,87 @@@
+"""
+This module provides a FastAPI application that uses Playwright to fetch and return
+the HTML content of a specified URL. It supports optional proxy settings and media blocking.
+"""
+
+from os import environ
+
from fastapi import FastAPI
-from playwright.async_api import async_playwright, Browser
from fastapi.responses import JSONResponse
+from playwright.async_api import Browser, async_playwright
from pydantic import BaseModel
-from os import environ
- 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'
+ 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"
app = FastAPI()
-
class UrlModel(BaseModel):
+ """Model representing the URL and associated parameters for the request."""
url: str
- wait: int = None
- wait_until: str = "load"
+ wait_after_load: int = 0
+ timeout: int = 15000
+ headers: dict = None
-
browser: Browser = None
-
@app.on_event("startup")
async def startup_event():
+ """Event handler for application startup to initialize the browser."""
global browser
playwright = await async_playwright().start()
browser = await playwright.chromium.launch()
-
@app.on_event("shutdown")
async def shutdown_event():
+ """Event handler for application shutdown to close the browser."""
await browser.close()
-
@app.post("/html")
async def root(body: UrlModel):
+ """
+ Endpoint to fetch and return HTML content of a given URL.
+
+ Args:
+ body (UrlModel): The URL model containing the target URL, wait time, and timeout.
+
+ Returns:
+ JSONResponse: The HTML content of the page.
+ """
context = None
if PROXY_SERVER and PROXY_USERNAME and PROXY_PASSWORD:
- context = await browser.new_context(proxy={"server": PROXY_SERVER,
- "username": PROXY_USERNAME,
- "password": PROXY_PASSWORD})
+ context = await browser.new_context(
+ proxy={
+ "server": PROXY_SERVER,
+ "username": PROXY_USERNAME,
+ "password": PROXY_PASSWORD,
+ }
+ )
else:
context = await browser.new_context()
if BLOCK_MEDIA:
- await context.route("**/*.{png,jpg,jpeg,gif,svg,mp3,mp4,avi,flac,ogg,wav,webm}",
- handler=lambda route, request: route.abort())
+ await context.route(
+ "**/*.{png,jpg,jpeg,gif,svg,mp3,mp4,avi,flac,ogg,wav,webm}",
+ handler=lambda route, request: route.abort(),
+ )
page = await context.new_page()
+
+ # Set headers if provided
+ if body.headers:
+ await page.set_extra_http_headers(body.headers)
+
await page.goto(
body.url,
- 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
+ wait_until="load",
+ timeout=body.timeout,
+ )
+ # Wait != timeout. Wait is the time to wait after the page is loaded - useful in some cases were "load" / "networkidle" is not enough
+ if body.wait_after_load > 0:
+ await page.wait_for_timeout(body.wait_after_load)
+
page_content = await page.content()
await context.close()
json_compatible_item_data = {"content": page_content}