Spaces:
Running
Running
File size: 2,326 Bytes
07b0738 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | import express from "express";
import { chromium } from "playwright";
const app = express();
const PORT = 7860;
app.get("/", (req, res) => {
res.json({
status: "running",
usage: "/search?q=openai"
});
});
app.get("/search", async (req, res) => {
const query = req.query.q;
if (!query) {
return res.status(400).json({
error: "Missing parameter q"
});
}
const browser = await chromium.launch({
headless: true,
args: [
"--no-sandbox",
"--disable-blink-features=AutomationControlled"
]
});
const context = await browser.newContext({
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/137.0.0.0 Safari/537.36",
viewport: {
width: 1366,
height: 768
}
});
const page = await context.newPage();
try {
await page.goto(
`https://www.google.com/search?q=${encodeURIComponent(query)}&hl=en`,
{
waitUntil: "networkidle",
timeout: 30000
}
);
const title = await page.title();
if (
title.toLowerCase().includes("sorry") ||
title.toLowerCase().includes("unusual")
) {
await browser.close();
return res.json({
error: "Google blocked this request",
pageTitle: title
});
}
const results = await page.evaluate(() => {
const data = [];
document.querySelectorAll("a").forEach(a => {
const h3 = a.querySelector("h3");
if (!h3) return;
if (!a.href.startsWith("http")) return;
data.push({
title: h3.innerText,
url: a.href
});
});
return data.slice(0, 10);
});
await browser.close();
res.json({
query,
count: results.length,
results
});
} catch (err) {
await browser.close();
res.status(500).json({
error: err.message
});
}
});
app.listen(PORT, () => {
console.log("Running on port", PORT);
}); |