stocks / modules /monitor /shared_browser.py
user
python version
ee446e8
Raw History Blame Contribute Delete
2 kB
"""Single shared headless Chromium instance for all experimental site
scrapers (momo_scraper.py, titan_scraper.py). Each scraper previously
launched its own browser process just to hold one page open -- that's two
full Chromium processes for two WebSocket connections. One shared browser
process with a separate BrowserContext per scraper (so cookies/UA stay
isolated) cuts that in half.
"""
import asyncio
from playwright.async_api import Browser, Playwright, async_playwright
_playwright: Playwright | None = None
_browser: Browser | None = None
_lock = asyncio.Lock()
async def get_browser() -> Browser:
global _playwright, _browser
async with _lock:
if _browser is None:
_playwright = await async_playwright().start()
_browser = await _playwright.chromium.launch(
headless=True,
args=[
"--disable-blink-features=AutomationControlled",
# Trims Chromium overhead we don't need for a headless
# tab that only exists to keep one WebSocket open --
# no GPU/compositor, no background services, no
# first-run/updater/telemetry work competing for CPU.
"--disable-gpu",
"--disable-dev-shm-usage",
"--disable-extensions",
"--disable-background-networking",
"--disable-sync",
"--disable-translate",
"--disable-default-apps",
"--metrics-recording-only",
"--mute-audio",
"--no-first-run",
],
)
return _browser
async def shutdown() -> None:
global _playwright, _browser
async with _lock:
if _browser is not None:
await _browser.close()
_browser = None
if _playwright is not None:
await _playwright.stop()
_playwright = None