from fastapi import FastAPI, HTTPException from pydantic import BaseModel import threading, queue, time from seleniumbase import SB app = FastAPI() class URLRequest(BaseModel): url: str url_queue = queue.Queue() sb_ref = {"driver": None} def browser_worker(): # ใช้เบราว์เซอร์จริง (ไม่ headless) แต่จอถูก Xvfb รับไว้จาก xvfb-run # ระบุ browser="chromium" ให้ตรงกับแพ็กเกจที่ติดตั้ง with SB(browser="chromium", uc=True, headless=False) as sb: sb_ref["driver"] = sb sb.get("https://www.google.com") while True: url = url_queue.get() try: print(f"[open] {url}") sb.get(url) time.sleep(0.3) except Exception as e: print("[error]", e) finally: url_queue.task_done() @app.get("/healthz") def healthz(): return {"ok": bool(sb_ref.get("driver"))} @app.get("/cookies") def get_cookies(): sb = sb_ref.get("driver") if not sb: raise HTTPException(503, "Browser not ready") return sb.get_cookies() @app.post("/open_url") async def open_url(request: URLRequest): if not sb_ref.get("driver"): raise HTTPException(503, "Browser not ready") print(f"[queue] {request.url}") url_queue.put(request.url) return {"status": "queued", "url": request.url} threading.Thread(target=browser_worker, daemon=True).start()