File size: 5,727 Bytes
6eef820 | 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | """Standalone FastAPI-сервис: headless-скрапер формы расчёта ПЭК.
Деплоится в Hugging Face Space (Docker SDK, порт 7860). Один полезный
эндпоинт POST /scrape: принимает агрегированные параметры груза и набор
CSS-селекторов pecom.ru, отдаёт {price_rub, days_min, days_max}.
Авторизация — Bearer-токен (env PEK_SCRAPER_TOKEN), общий с основным
FastAPI на Vercel. Stateless: ни БД, ни кэша — кэширование живёт на
стороне основного приложения (PekCachedQuote, TTL 24ч).
"""
from __future__ import annotations
import logging
import os
import re
from decimal import Decimal, InvalidOperation
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
app = FastAPI(title="PEK Scraper", version="1.0.0")
_PRICE_DIGITS = re.compile(r"[\d\s.,]+")
_DAYS_RANGE = re.compile(r"(\d+)\s*[-–—]\s*(\d+)")
_DAYS_SINGLE = re.compile(r"(\d+)")
class ScrapeRequest(BaseModel):
"""Параметры запроса к ПЭК. Селекторы передаются клиентом — менять без передеплоя."""
city: str = Field(..., min_length=1, max_length=100)
weight_kg: str
volume_m3: str
places_count: int = Field(..., ge=1, le=1000)
selectors: dict[str, str]
class ScrapeResponse(BaseModel):
price_rub: str
days_min: int
days_max: int
async def verify_token(authorization: Annotated[str, Header()] = "") -> None:
"""Проверяет Bearer-токен из заголовка против env PEK_SCRAPER_TOKEN."""
expected = os.environ.get("PEK_SCRAPER_TOKEN", "")
if not expected:
raise HTTPException(status_code=503, detail="PEK_SCRAPER_TOKEN не задан в env")
if authorization != f"Bearer {expected}":
raise HTTPException(status_code=401, detail="invalid token")
def _parse_price_rub(text: str) -> Decimal:
if not text:
raise ValueError("пустой текст цены")
match = _PRICE_DIGITS.search(text)
if not match:
raise ValueError(f"не нашёл цифр в цене: {text!r}")
cleaned = match.group(0).strip().replace(" ", "").replace(" ", "").replace(",", ".")
if cleaned.count(".") > 1:
head, _, tail = cleaned.rpartition(".")
cleaned = head.replace(".", "") + "." + tail
try:
return Decimal(cleaned)
except InvalidOperation as exc:
raise ValueError(f"не распарсил цену: {text!r}") from exc
def _parse_days_range(text: str) -> tuple[int, int]:
if not text:
raise ValueError("пустой текст срока")
m = _DAYS_RANGE.search(text)
if m:
return int(m.group(1)), int(m.group(2))
m = _DAYS_SINGLE.search(text)
if m:
n = int(m.group(1))
return n, n
raise ValueError(f"не распарсил срок: {text!r}")
_PEK_FORM_URL = "https://pecom.ru/services-are/shipping-request/"
_DEFAULT_TIMEOUT_MS = 15000
@app.get("/health")
async def health() -> dict[str, bool]:
return {"ok": True}
@app.post("/scrape", response_model=ScrapeResponse, dependencies=[Depends(verify_token)])
async def scrape(req: ScrapeRequest) -> ScrapeResponse:
"""Открывает форму pecom.ru, заполняет, парсит результат."""
try:
from playwright.async_api import ( # type: ignore[import-not-found]
TimeoutError as PlaywrightTimeoutError,
)
from playwright.async_api import async_playwright
except ImportError as exc:
raise HTTPException(status_code=503, detail=f"playwright not installed: {exc}") from exc
sel = req.selectors
try:
async with async_playwright() as pw:
browser = await pw.chromium.launch(headless=True)
try:
page = await browser.new_page()
page.set_default_timeout(_DEFAULT_TIMEOUT_MS)
await page.goto(_PEK_FORM_URL)
await page.fill(sel["from_city"], "Алматы")
await page.fill(sel["to_city"], req.city)
await page.fill(sel["weight"], req.weight_kg)
await page.fill(sel["volume"], req.volume_m3)
await page.fill(sel["places"], str(req.places_count))
await page.click(sel["submit"])
await page.wait_for_selector(sel["result_price"], timeout=_DEFAULT_TIMEOUT_MS)
price_text = (await page.text_content(sel["result_price"])) or ""
days_text = (await page.text_content(sel["result_days"])) or ""
finally:
await browser.close()
except PlaywrightTimeoutError as exc:
logger.warning("PEK form timeout for %s: %s", req.city, exc)
raise HTTPException(status_code=502, detail=f"pek timeout: {exc}") from exc
except KeyError as exc:
raise HTTPException(status_code=400, detail=f"missing selector: {exc}") from exc
except Exception as exc:
logger.warning("PEK scrape failed for %s: %s", req.city, exc)
raise HTTPException(status_code=502, detail=f"pek scrape failed: {exc}") from exc
try:
price = _parse_price_rub(price_text)
days_min, days_max = _parse_days_range(days_text)
except ValueError as exc:
raise HTTPException(status_code=502, detail=f"parse failed: {exc}") from exc
return ScrapeResponse(price_rub=str(price), days_min=days_min, days_max=days_max)
|