apexherbert200's picture
Using google search
be7cc52
raw
history blame
1.3 kB
from fastapi import FastAPI
from playwright.async_api import async_playwright
app = FastAPI()
async def scrape_google(query: str):
url = (
"https://www.google.com/search"
f"?q={query}"
"&sxsrf=AE3TifOZcTbH54cOkE27wqRqSVEmaqb7fw%3A1750003707838"
)
async with async_playwright() as pw:
browser = await pw.chromium.launch(headless=True)
context = await browser.new_context()
page = await context.new_page()
# Accept cookie/consent pop-ups
try:
btn = await page.wait_for_selector('button:has-text("I agree")', timeout=5000)
await btn.click()
except:
pass
await page.goto(url, wait_until="domcontentloaded")
await page.wait_for_selector("h3")
results = []
for h in await page.query_selector_all("h3"):
try:
link = await h.evaluate("(e) => e.closest('a').href")
title = await h.inner_text()
results.append({"title": title, "link": link})
except:
continue
await browser.close()
return results
@app.get("/search")
async def search(query: str):
data = await scrape_google(query.replace(" ", "+"))
return {"query": query, "results": data}