extsearch 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
extsearch/catalog.py ADDED
@@ -0,0 +1,1122 @@
1
+ """Ukrainian shops: Prom, Foxtrot, Rozetka, Comfy, Allo, Moyo, Kasta, Brain, Citrus.
2
+
3
+ Anti-bot rules (verified empirically on 2026-11-09):
4
+
5
+ site | plain curl/libcurl | impersonate=chrome
6
+ ----------|--------------------|-------------------
7
+ Prom.ua | 200, full results | 200 but an empty placeholder
8
+ Foxtrot | 200, full results | not tested
9
+ Rozetka | 403 | product API works
10
+
11
+ That is why there are two separate HTTP clients: plain (Prom, Foxtrot) and
12
+ chrome (Rozetka API). Mixing them breaks everything.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ import re
20
+ import time
21
+ import urllib.parse
22
+ from typing import Any
23
+
24
+ from bs4 import BeautifulSoup
25
+ from curl_cffi import requests as ccreq
26
+ from curl_cffi.requests.exceptions import RequestException
27
+
28
+ from . import details
29
+ from .errors import ExtSearchError as OlxError
30
+ from .proxies import for_request
31
+
32
+ TIMEOUT = 30.0
33
+ MIN_INTERVAL = 0.5
34
+ CACHE_TTL = 300
35
+
36
+ _plain: "ccreq.AsyncSession | None" = None
37
+ _chrome: "ccreq.AsyncSession | None" = None
38
+ _safari: "ccreq.AsyncSession | None" = None
39
+ _lock: asyncio.Lock | None = None
40
+ _last = 0.0
41
+ _cache: dict[str, tuple[float, Any]] = {}
42
+
43
+ # id -> url so market_get can open a card without a second search
44
+ _URLS: dict[tuple[str, int], str] = {}
45
+ # id -> search row: some shops render the price only via JS, and then it is
46
+ # more honest to reuse the search price than to return null
47
+ _ROWS: dict[tuple[str, int], dict[str, Any]] = {}
48
+
49
+
50
+ def _client(chrome: bool) -> "ccreq.AsyncSession":
51
+ global _plain, _chrome
52
+ if chrome:
53
+ if _chrome is None:
54
+ _chrome = ccreq.AsyncSession(impersonate="chrome", timeout=TIMEOUT)
55
+ return _chrome
56
+ if _plain is None:
57
+ _plain = ccreq.AsyncSession(timeout=TIMEOUT)
58
+ return _plain
59
+
60
+
61
+ def _safari_client() -> "ccreq.AsyncSession":
62
+ """Fallback TLS profile.
63
+
64
+ Comfy (and sometimes other Cloudflare sites) started answering 403 to the
65
+ chrome fingerprint while Safari passes. A separate session keeps the main
66
+ client untouched.
67
+ """
68
+ global _safari
69
+ if _safari is None:
70
+ _safari = ccreq.AsyncSession(impersonate="safari", timeout=TIMEOUT)
71
+ return _safari
72
+
73
+
74
+ async def _throttle() -> None:
75
+ global _lock, _last
76
+ if _lock is None:
77
+ _lock = asyncio.Lock()
78
+ async with _lock:
79
+ wait = MIN_INTERVAL - (time.monotonic() - _last)
80
+ if wait > 0:
81
+ await asyncio.sleep(wait)
82
+ _last = time.monotonic()
83
+
84
+
85
+ async def _fetch(url: str, params: dict[str, Any] | None = None, *,
86
+ chrome: bool = False, as_json: bool = False,
87
+ retries: int = 2) -> Any:
88
+ key = f"{'c' if chrome else 'p'}:{url}:{json.dumps(params or {}, sort_keys=True)}"
89
+ hit = _cache.get(key)
90
+ if hit and time.monotonic() < hit[0]:
91
+ return hit[1]
92
+
93
+ client = _client(chrome)
94
+ last_err: OlxError | None = None
95
+
96
+ for attempt in range(retries + 1):
97
+ await _throttle()
98
+ try:
99
+ resp = await client.get(url, params=params,
100
+ proxies=for_request())
101
+ except RequestException as exc:
102
+ last_err = OlxError("network", f"network request failed: {exc}")
103
+ await asyncio.sleep(1.5 * (attempt + 1))
104
+ continue
105
+
106
+ if resp.status_code in (401, 403) and chrome:
107
+ # The TLS fingerprint is the first suspect. One Safari attempt is
108
+ # cheaper than reporting the whole shop as blocked.
109
+ await _throttle()
110
+ try:
111
+ resp = await _safari_client().get(url, params=params,
112
+ proxies=for_request())
113
+ except RequestException as exc:
114
+ last_err = OlxError("network", f"network request failed: {exc}")
115
+ await asyncio.sleep(1.5 * (attempt + 1))
116
+ continue
117
+
118
+ if resp.status_code == 404:
119
+ raise OlxError("not_found", "page not found")
120
+ if resp.status_code in (401, 403):
121
+ raise OlxError(
122
+ "blocked",
123
+ f"{urllib.parse.urlsplit(url).hostname} blocked the request (HTTP 403). "
124
+ "Rozetka needs a warmed browser profile; the other shops usually "
125
+ "fail when impersonate is enabled.",
126
+ )
127
+ if resp.status_code == 429:
128
+ last_err = OlxError("rate_limited", "HTTP 429: rate limited")
129
+ await asyncio.sleep(4 * (attempt + 1))
130
+ continue
131
+ if resp.status_code >= 500:
132
+ last_err = OlxError("server_error", f"HTTP {resp.status_code}")
133
+ await asyncio.sleep(2 * (attempt + 1))
134
+ continue
135
+
136
+ value: Any = resp.json() if as_json else resp.text
137
+ if len(_cache) > 256:
138
+ _cache.clear()
139
+ _cache[key] = (time.monotonic() + CACHE_TTL, value)
140
+ return value
141
+
142
+ raise last_err or OlxError("unknown", "could not fetch the page")
143
+
144
+
145
+ # --------------------------------------------------------------------------
146
+ # Shared helpers
147
+ # --------------------------------------------------------------------------
148
+
149
+ _WORD_RE = re.compile(r"[0-9a-zа-яіїєґё]+", re.IGNORECASE)
150
+ _SPACES_RE = re.compile(r"[ \t\u00a0]+")
151
+
152
+
153
+ def _relevance(query: str, title: str) -> float:
154
+ want = {w for w in _WORD_RE.findall(query.lower()) if len(w) > 1}
155
+ if not want:
156
+ return 1.0
157
+ have = set(_WORD_RE.findall(title.lower()))
158
+ return round(len(want & have) / len(want), 3)
159
+
160
+
161
+ def _price_from_text(raw: str | None) -> int | None:
162
+ if not raw:
163
+ return None
164
+ digits = re.sub(r"[^\d]", "", _SPACES_RE.sub(" ", raw).split("₴")[0].split("грн")[0])
165
+ return int(digits) if digits else None
166
+
167
+
168
+ def _remember(source: str, offer_id: Any, url: str | None,
169
+ row: dict[str, Any] | None = None) -> None:
170
+ if not offer_id:
171
+ return
172
+ if len(_URLS) > 2048:
173
+ _URLS.clear()
174
+ _ROWS.clear()
175
+ if url:
176
+ _URLS[(source, str(offer_id))] = url
177
+ if row is not None:
178
+ _ROWS[(source, str(offer_id))] = dict(row)
179
+
180
+
181
+ def _cached_row(source: str, offer_id: int) -> dict[str, Any]:
182
+ return _ROWS.get((source, str(offer_id))) or {}
183
+
184
+
185
+ def _fetch_url(source: str, offer_id: int) -> str:
186
+ url = _URLS.get((source, str(offer_id)))
187
+ if not url:
188
+ raise OlxError(
189
+ "no_url",
190
+ f"no known URL for {source}:{offer_id}; run a search on this "
191
+ "marketplace first, item URLs are remembered from search results.",
192
+ )
193
+ return url
194
+
195
+
196
+ def _longest_link(card: Any, needle: str) -> Any:
197
+ """Longest-text link: separates the product card from icon links."""
198
+ best = None
199
+ best_len = -1
200
+ for a in card.select("a[href]"):
201
+ href = a.get("href") or ""
202
+ if needle not in href:
203
+ continue
204
+ size = len(a.get_text(strip=True))
205
+ if size > best_len:
206
+ best, best_len = a, size
207
+ return best
208
+
209
+
210
+ def _int_from(text: str | None) -> int | None:
211
+ if not text:
212
+ return None
213
+ digits = re.sub(r"\D", "", text)
214
+ return int(digits) if digits else None
215
+
216
+
217
+ def _rating(row: dict[str, Any], card: Any, *, rating_sel: str | None,
218
+ reviews_sel: str | None) -> None:
219
+ """Add rating/reviews to a search row when the markup provides them."""
220
+ if rating_sel:
221
+ el = card.select_one(rating_sel)
222
+ if el is not None:
223
+ try:
224
+ row["rating"] = float(el.get_text(strip=True).replace(",", ".")[:4])
225
+ except ValueError:
226
+ pass
227
+ if reviews_sel:
228
+ el = card.select_one(reviews_sel)
229
+ if el is not None:
230
+ count = _int_from(el.get_text(strip=True))
231
+ if count is not None:
232
+ row["reviews_count"] = count
233
+
234
+
235
+ def _finish(rows: list[dict[str, Any]], *, total: int, page: int, limit: int,
236
+ price_min: int | None, price_max: int | None, sort: str | None,
237
+ strict: bool, query: str, source: str,
238
+ include_urls: bool = False) -> dict[str, Any]:
239
+ """Shared post-processing: price filter, strict mode, sorting."""
240
+ out = []
241
+ for row in rows:
242
+ if price_min is not None and (row["price"] is None or row["price"] < price_min):
243
+ continue
244
+ if price_max is not None and (row["price"] is None or row["price"] > price_max):
245
+ continue
246
+ if strict and row["relevance"] <= 0:
247
+ continue
248
+ if include_urls:
249
+ row["url"] = _URLS.get((source, str(row["id"])))
250
+ out.append(row)
251
+
252
+ # Remember search rows: some shops (Allo) render the price only via JS and
253
+ # the product card has no price to read.
254
+ for row in out:
255
+ try:
256
+ _ROWS[(source, str(row["id"]))] = dict(row)
257
+ except (KeyError, TypeError, ValueError):
258
+ continue
259
+
260
+ if sort == "cheapest":
261
+ out.sort(key=lambda r: (r["price"] is None, r["price"] or 0))
262
+ elif sort == "expensive":
263
+ out.sort(key=lambda r: (r["price"] is None, -(r["price"] or 0)))
264
+ elif sort in ("rating", "rating_asc"):
265
+ # Items without a rating go last, so "best reviews" does not start with
266
+ # empty cards.
267
+ out.sort(key=lambda r: (r.get("rating") is None,
268
+ -r.get("rating", 0) if sort == "rating"
269
+ else r.get("rating", 0)))
270
+ elif sort in (None, "relevance", ""):
271
+ out.sort(key=lambda r: -r["relevance"])
272
+
273
+ return {
274
+ "source": source,
275
+ "query": query,
276
+ "page": page,
277
+ "limit": limit,
278
+ "returned": len(out),
279
+ "total": total,
280
+ "items": out[:limit],
281
+ }
282
+
283
+
284
+ # --------------------------------------------------------------------------
285
+ # Prom.ua — HTML, stable data-qaid anchors
286
+ # --------------------------------------------------------------------------
287
+
288
+ PROM_SEARCH = "https://prom.ua/ua/search"
289
+ _PROM_ID_RE = re.compile(r"/m-?(\d+)-") # some products use a negative id: /ua/m-4104...
290
+
291
+
292
+ async def prom_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
293
+ html = await _fetch(PROM_SEARCH, {"search_term": query, "page": page})
294
+ soup = BeautifulSoup(html, "html.parser")
295
+ rows: list[dict[str, Any]] = []
296
+
297
+ for link in soup.select('a[data-qaid="product_link"]'):
298
+ href = link.get("href") or ""
299
+ m = _PROM_ID_RE.search(href)
300
+ if not m:
301
+ continue
302
+ title_el = link.select_one('[data-qaid="product_name"]')
303
+ title = (title_el.get_text(strip=True) if title_el else "") or link.get("title", "")
304
+
305
+ # price/presence live in the card ancestor, not inside the link
306
+ node = link.parent
307
+ price_raw = None
308
+ presence = None
309
+ for _ in range(6):
310
+ if node is None:
311
+ break
312
+ pe = node.select_one('[data-qaid="product_price"]')
313
+ if pe is not None:
314
+ price_raw = pe.get("data-qaprice") or pe.get_text(strip=True)
315
+ pr = node.select_one('[data-qaid="product_presence"]')
316
+ presence = pr.get_text(strip=True) if pr else None
317
+ break
318
+ node = node.parent
319
+
320
+ offer_id = int(m.group(1))
321
+ url = href if href.startswith("http") else f"https://prom.ua{href}"
322
+ _remember("prom", offer_id, url)
323
+ rows.append({
324
+ "id": offer_id,
325
+ "title": title,
326
+ "price": _price_from_text(price_raw),
327
+ "currency": "UAH",
328
+ "state": None,
329
+ "availability": presence,
330
+ "city": None,
331
+ "business": True,
332
+ "relevance": _relevance(query, title),
333
+ })
334
+
335
+ return rows
336
+
337
+
338
+ async def prom_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
339
+ url = _fetch_url("prom", offer_id)
340
+ html = await _fetch(url)
341
+ soup = BeautifulSoup(html, "html.parser")
342
+
343
+ h1 = soup.select_one("h1")
344
+ title = h1.get_text(strip=True) if h1 else None
345
+ if not title:
346
+ og = soup.select_one("meta[property='og:title']")
347
+ if og is not None and og.get("content"):
348
+ title = og["content"].strip()
349
+ elif soup.title is not None:
350
+ title = soup.title.get_text(strip=True) or None
351
+
352
+ price = None
353
+ for sel in ('[data-qaid="product_price"]', ".b-product-price__value",
354
+ '[itemprop="price"]'):
355
+ el = soup.select_one(sel)
356
+ if el is not None:
357
+ price = _price_from_text(el.get("content") or el.get("data-qaprice")
358
+ or el.get_text(strip=True))
359
+ if price is not None:
360
+ break
361
+
362
+ desc_el = soup.select_one('[data-qaid="descriptions"], [data-qaid="product_description"], #description')
363
+ description = desc_el.get_text(" ", strip=True) if desc_el else ""
364
+ if max_description_chars and len(description) > max_description_chars:
365
+ description = description[:max_description_chars].rstrip() + "…"
366
+
367
+ seller = None
368
+ s_el = soup.select_one('[data-qaid="company_name"], .b-seller__title')
369
+ if s_el:
370
+ seller = s_el.get_text(strip=True)
371
+
372
+ result = {
373
+ "source": "prom",
374
+ "id": offer_id,
375
+ "title": title,
376
+ "price": price,
377
+ "currency": "UAH",
378
+ "description": description,
379
+ "seller": seller,
380
+ "url": url,
381
+ }
382
+ result.update(details.enrich(html, details.SHOPS["prom"], soup=soup))
383
+ return result
384
+
385
+
386
+ # --------------------------------------------------------------------------
387
+ # Foxtrot — HTML, stable product-card__* classes
388
+ # --------------------------------------------------------------------------
389
+
390
+ FOXTROT_SEARCH = "https://www.foxtrot.com.ua/uk/search"
391
+ _FX_CODE_RE = re.compile(r"(\d{5,9})")
392
+
393
+
394
+ async def foxtrot_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
395
+ params = {"query": query}
396
+ if page > 1:
397
+ params["page"] = page
398
+ html = await _fetch(FOXTROT_SEARCH, params)
399
+ soup = BeautifulSoup(html, "html.parser")
400
+ rows: list[dict[str, Any]] = []
401
+ seen: set[int] = set()
402
+
403
+ for card in soup.select("div.product-card"):
404
+ title_el = card.select_one(".product-card__title")
405
+ link_el = card.select_one("a[data-ecom]") or card.select_one("a[href*='/shop/']")
406
+ if not (title_el and link_el):
407
+ continue
408
+ href = link_el.get("href") or ""
409
+ code_el = card.select_one(".info-article")
410
+ code = None
411
+ if code_el:
412
+ m = _FX_CODE_RE.search(code_el.get_text())
413
+ code = int(m.group(1)) if m else None
414
+ if code is None:
415
+ m = _FX_CODE_RE.search(href.replace(".html", "")[::-1])
416
+ code = int(m.group(1)[::-1]) if m else None
417
+ if code is None or code in seen:
418
+ continue
419
+ seen.add(code)
420
+
421
+ price_el = card.select_one(".price--current") or card.select_one(".product-prices")
422
+ out_of_stock = card.select_one(".product-card__button[disabled]") is not None
423
+ title = title_el.get_text(strip=True)
424
+ url = href if href.startswith("http") else f"https://www.foxtrot.com.ua{href}"
425
+ _remember("foxtrot", code, url)
426
+ rows.append({
427
+ "id": code,
428
+ "title": title,
429
+ "price": _price_from_text(price_el.get_text() if price_el else None),
430
+ "currency": "UAH",
431
+ "state": None,
432
+ "availability": "out of stock" if out_of_stock else "in stock",
433
+ "city": None,
434
+ "business": True,
435
+ "relevance": _relevance(query, title),
436
+ })
437
+
438
+ return rows[: max(limit * 2, 20)]
439
+
440
+
441
+ async def foxtrot_get(code: int, max_description_chars: int = 600) -> dict[str, Any]:
442
+ url = _fetch_url("foxtrot", code)
443
+ html = await _fetch(url)
444
+ soup = BeautifulSoup(html, "html.parser")
445
+
446
+ h1 = soup.select_one("h1")
447
+ title = h1.get_text(strip=True) if h1 else None
448
+ price_el = soup.select_one(".price--current, .product-prices__price, [itemprop='price']")
449
+ price = _price_from_text(price_el.get("content") or price_el.get_text()
450
+ if price_el else None)
451
+
452
+ desc_el = soup.select_one(".pdp-description, .pdp-short-description, "
453
+ "[itemprop='description'], .product-about__text")
454
+ description = desc_el.get_text(" ", strip=True) if desc_el else ""
455
+ if max_description_chars and len(description) > max_description_chars:
456
+ description = description[:max_description_chars].rstrip() + "…"
457
+
458
+ result = {
459
+ "source": "foxtrot",
460
+ "id": code,
461
+ "title": title,
462
+ "price": price,
463
+ "currency": "UAH",
464
+ "description": description,
465
+ "url": url,
466
+ }
467
+ result.update(details.enrich(html, details.SHOPS["foxtrot"], soup=soup))
468
+ return result
469
+
470
+
471
+ # --------------------------------------------------------------------------
472
+ # Rozetka — the product API works, search needs a live browser session
473
+ # --------------------------------------------------------------------------
474
+
475
+ ROZETKA_GOODS = "https://rozetka.com.ua/api/product-api/v4/goods/get-main"
476
+ ROZETKA_SEARCH_PAGE = "https://rozetka.com.ua/ua/search/"
477
+
478
+
479
+ async def rozetka_get(goods_id: int) -> dict[str, Any]:
480
+ payload = await _fetch(
481
+ ROZETKA_GOODS,
482
+ {"front-type": "xl", "country": "UA", "lang": "ua", "goodsId": int(goods_id)},
483
+ chrome=True, as_json=True,
484
+ )
485
+ item = (payload or {}).get("data")
486
+ if not isinstance(item, dict):
487
+ raise OlxError("not_found", f"Rozetka: product {goods_id} not found")
488
+
489
+ result = {
490
+ "source": "rozetka",
491
+ "id": item.get("id"),
492
+ "title": item.get("title"),
493
+ "price": int(item["price"]) if isinstance(item.get("price"), (int, float)) else None,
494
+ "old_price": item.get("old_price") or None,
495
+ "currency": "UAH",
496
+ "status": item.get("status"),
497
+ "sell_status": item.get("sell_status"),
498
+ "rating": item.get("comments_mark"),
499
+ "reviews": item.get("comments_amount"),
500
+ "category_id": item.get("category_id"),
501
+ "url": item.get("href"),
502
+ }
503
+ # The product page is behind Cloudflare, so delivery/payment come from
504
+ # the shop passport and the rating from the same API response.
505
+ result.update(details.enrich("", details.SHOPS["rozetka"]))
506
+ if item.get("comments_mark") is not None or item.get("comments_amount"):
507
+ result["reviews_info"] = {
508
+ "rating": item.get("comments_mark"),
509
+ "count": item.get("comments_amount"),
510
+ }
511
+ result["reviews"] = result.pop("reviews")
512
+ return result
513
+
514
+
515
+ async def rozetka_search(query: str, limit: int = 10, page: int = 1,
516
+ profile_dir: str | None = None,
517
+ timeout_ms: int = 25000) -> list[dict[str, Any]]:
518
+ """Rozetka search through a real browser.
519
+
520
+ Rozetka sits behind a Cloudflare challenge: neither curl nor headless
521
+ without cookies gets through. A persistent profile with the challenge
522
+ already solved is required (open the site once in that profile by hand).
523
+
524
+ Data is not taken from the DOM (unstable classes): the page is rendered,
525
+ goodsId values are extracted from links like /123456789/p123456789/, and the
526
+ working get-main API enriches them. Parsing then survives layout changes.
527
+ """
528
+ try:
529
+ from playwright.async_api import async_playwright
530
+ except ImportError as exc:
531
+ raise OlxError(
532
+ "browser_unavailable",
533
+ f"Playwright is not available ({exc}). Install the browser "
534
+ "extra: pip install playwright && playwright install chromium",
535
+ )
536
+
537
+ import os
538
+ from pathlib import Path
539
+
540
+ profile = Path(profile_dir or os.environ.get(
541
+ "ROZETKA_PROFILE", Path.home() / ".local/share/ua-marketplace/rz-profile"))
542
+ profile.mkdir(parents=True, exist_ok=True)
543
+
544
+ params = {"text": query}
545
+ if page > 1:
546
+ params["page"] = page
547
+ url = ROZETKA_SEARCH_PAGE + "?" + urllib.parse.urlencode(params)
548
+
549
+ try:
550
+ async with async_playwright() as p:
551
+ ctx = await p.chromium.launch_persistent_context(
552
+ str(profile), headless=os.environ.get("ROZETKA_HEADFUL") != "1",
553
+ locale="uk-UA", viewport={"width": 1440, "height": 900},
554
+ )
555
+ try:
556
+ page_obj = ctx.pages[0] if ctx.pages else await ctx.new_page()
557
+ await page_obj.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
558
+ try:
559
+ await page_obj.wait_for_selector(
560
+ 'a[href*="/p"]:has(img), rz-product-catalog, .catalog-grid',
561
+ timeout=timeout_ms,
562
+ )
563
+ except Exception:
564
+ pass
565
+ html = await page_obj.content()
566
+ finally:
567
+ await ctx.close()
568
+ except OlxError:
569
+ raise
570
+ except Exception as exc: # noqa: BLE001
571
+ # Playwright raises its own Error when the browser is not installed.
572
+ raise OlxError(
573
+ "browser_unavailable",
574
+ f"browser engine is unavailable ({exc}). "
575
+ "Run: python -m playwright install chromium",
576
+ )
577
+
578
+ ids: list[int] = []
579
+ for m in re.finditer(r"/(\d{6,10})/p\d{6,10}/", html):
580
+ gid = int(m.group(1))
581
+ if gid not in ids:
582
+ ids.append(gid)
583
+
584
+ if not ids:
585
+ raise OlxError(
586
+ "needs_session",
587
+ "Rozetka returned a page without products — the Cloudflare challenge was not passed. "
588
+ "Run tools/warmup_rozetka.py once from a desktop terminal: a window "
589
+ "opens, pass the challenge, and the cookies stay in the profile.",
590
+ )
591
+
592
+ rows: list[dict[str, Any]] = []
593
+ for gid in ids[:limit]:
594
+ try:
595
+ data = await rozetka_get(gid)
596
+ except OlxError:
597
+ continue
598
+ rows.append({
599
+ "id": gid,
600
+ "title": data.get("title"),
601
+ "price": data.get("price"),
602
+ "currency": "UAH",
603
+ "state": data.get("status"),
604
+ "availability": data.get("sell_status"),
605
+ "city": None,
606
+ "business": True,
607
+ "relevance": _relevance(query, data.get("title") or ""),
608
+ "url": data.get("url"),
609
+ })
610
+ return rows
611
+
612
+
613
+ # --------------------------------------------------------------------------
614
+ # Comfy — electronics, HTML + chrome impersonate (plain gets 403)
615
+ # --------------------------------------------------------------------------
616
+
617
+ COMFY_SEARCH = "https://comfy.ua/ua/search/"
618
+
619
+
620
+ async def comfy_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
621
+ params: dict[str, Any] = {"q": query}
622
+ if page > 1:
623
+ params["page"] = page
624
+ html = await _fetch(COMFY_SEARCH, params, chrome=True)
625
+ soup = BeautifulSoup(html, "html.parser")
626
+ rows: list[dict[str, Any]] = []
627
+
628
+ for card in soup.select("div.product-tile-catalog"):
629
+ title_el = card.select_one(".product-tile-title__name")
630
+ link = _longest_link(card, ".html")
631
+ if title_el is None or link is None:
632
+ continue
633
+ title = title_el.get_text(strip=True)
634
+ code = _int_from((card.select_one(".product-tile-preview__sku") or card).get_text()) \
635
+ if card.select_one(".product-tile-preview__sku") else None
636
+ href = link.get("href") or ""
637
+ url = href if href.startswith("http") else f"https://comfy.ua{href}"
638
+ if code is None:
639
+ code = _int_from(url.rsplit("/", 1)[-1])
640
+ if code is None:
641
+ continue
642
+ _remember("comfy", code, url)
643
+ row = {
644
+ "id": code,
645
+ "title": title,
646
+ "price": _price_from_text((card.select_one(".product-tile-price__current") or card).get_text()
647
+ if card.select_one(".product-tile-price__current") else None),
648
+ "currency": "UAH",
649
+ "state": None,
650
+ "availability": None,
651
+ "city": None,
652
+ "business": True,
653
+ "relevance": _relevance(query, title),
654
+ }
655
+ old_el = card.select_one(".product-tile-price__old")
656
+ if old_el is not None:
657
+ row["old_price"] = _price_from_text(old_el.get_text())
658
+ _rating(row, card, rating_sel=".rating-number-box__value",
659
+ reviews_sel=".product-tile-feedback__reviews")
660
+ rows.append(row)
661
+
662
+ return rows[: max(limit * 2, 20)]
663
+
664
+
665
+ async def comfy_get(code: int, max_description_chars: int = 600) -> dict[str, Any]:
666
+ return await _product_page(code, "comfy", max_description_chars,
667
+ title_sel="h1",
668
+ price_sel=".price__current, .product-tile-price__current, [itemprop='price']",
669
+ desc_sel=".product-description, .pdp-description, [itemprop='description']")
670
+
671
+
672
+ # --------------------------------------------------------------------------
673
+ # Allo — electronics, HTML + chrome
674
+ # --------------------------------------------------------------------------
675
+
676
+ ALLO_SEARCH = "https://allo.ua/ua/catalogsearch/result/"
677
+
678
+
679
+ async def allo_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
680
+ params: dict[str, Any] = {"q": query}
681
+ if page > 1:
682
+ params["page"] = page
683
+ html = await _fetch(ALLO_SEARCH, params, chrome=True)
684
+ soup = BeautifulSoup(html, "html.parser")
685
+ rows: list[dict[str, Any]] = []
686
+
687
+ for card in soup.select(".product-card"):
688
+ title_el = card.select_one(".product-card__title")
689
+ link = _longest_link(card, "allo.ua")
690
+ if title_el is None or link is None:
691
+ continue
692
+ title = title_el.get_text(strip=True)
693
+ href = link.get("href") or ""
694
+ url = href if href.startswith("http") else f"https://allo.ua{href}"
695
+ sku = card.select_one(".product-sku__value")
696
+ offer_id = _int_from(sku.get_text() if sku else None)
697
+ if offer_id is None:
698
+ continue
699
+ _remember("allo", offer_id, url)
700
+ row = {
701
+ "id": offer_id,
702
+ "title": title,
703
+ "price": _price_from_text((card.select_one(".v-pb__cur") or card).get_text()
704
+ if card.select_one(".v-pb__cur") else None),
705
+ "currency": "UAH",
706
+ "state": None,
707
+ "availability": None,
708
+ "city": None,
709
+ "business": True,
710
+ "relevance": _relevance(query, title),
711
+ }
712
+ old_el = card.select_one(".v-pb__old")
713
+ if old_el is not None:
714
+ row["old_price"] = _price_from_text(old_el.get_text())
715
+ rows.append(row)
716
+
717
+ return rows[: max(limit * 2, 20)]
718
+
719
+
720
+ async def allo_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
721
+ return await _product_page(offer_id, "allo", max_description_chars,
722
+ title_sel="h1",
723
+ price_sel=".v-pb__cur, .p-price, [itemprop='price']",
724
+ desc_sel=".p-description, [itemprop='description']")
725
+
726
+
727
+ # --------------------------------------------------------------------------
728
+ # Moyo — electronics and home goods, HTML + chrome
729
+ # --------------------------------------------------------------------------
730
+
731
+ MOYO_SEARCH = "https://www.moyo.ua/ua/search/new/"
732
+
733
+
734
+ async def moyo_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
735
+ params: dict[str, Any] = {"q": query}
736
+ if page > 1:
737
+ params["page"] = page
738
+ html = await _fetch(MOYO_SEARCH, params, chrome=True)
739
+ soup = BeautifulSoup(html, "html.parser")
740
+ rows: list[dict[str, Any]] = []
741
+
742
+ for card in soup.select(".product-card"):
743
+ title_el = card.select_one(".product-card_title")
744
+ link = _longest_link(card, ".html")
745
+ if title_el is None or link is None:
746
+ continue
747
+ title = title_el.get_text(strip=True)
748
+ href = link.get("href") or ""
749
+ url = href if href.startswith("http") else f"https://www.moyo.ua{href}"
750
+ offer_id = _int_from(url.rsplit("/", 1)[-1])
751
+ if offer_id is None or offer_id <= 0:
752
+ continue
753
+ _remember("moyo", offer_id, url)
754
+ row = {
755
+ "id": offer_id,
756
+ "title": title,
757
+ "price": _price_from_text((card.select_one(".product-card_price_current") or card).get_text()
758
+ if card.select_one(".product-card_price_current") else None),
759
+ "currency": "UAH",
760
+ "state": None,
761
+ "availability": None,
762
+ "city": None,
763
+ "business": True,
764
+ "relevance": _relevance(query, title),
765
+ }
766
+ old_el = card.select_one(".product-card_price_oldprice")
767
+ if old_el is not None:
768
+ row["old_price"] = _price_from_text(old_el.get_text())
769
+ rows.append(row)
770
+
771
+ return rows[: max(limit * 2, 20)]
772
+
773
+
774
+ async def moyo_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
775
+ return await _product_page(offer_id, "moyo", max_description_chars,
776
+ title_sel="h1",
777
+ price_sel=".product-card_price_current, .price--current, [itemprop='price']",
778
+ desc_sel=".product-description, .js-product-description, [itemprop='description']")
779
+
780
+
781
+ # --------------------------------------------------------------------------
782
+ # Kasta — fashion, beauty, electronics, HTML + chrome
783
+ # --------------------------------------------------------------------------
784
+
785
+ KASTA_SEARCH = "https://kasta.ua/uk/search/"
786
+
787
+
788
+ async def kasta_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
789
+ params: dict[str, Any] = {"q": query}
790
+ if page > 1:
791
+ params["page"] = page
792
+ html = await _fetch(KASTA_SEARCH, params, chrome=True)
793
+ soup = BeautifulSoup(html, "html.parser")
794
+ rows: list[dict[str, Any]] = []
795
+
796
+ for card in soup.select("article.p__item"):
797
+ link = _longest_link(card, "/product/")
798
+ if link is None:
799
+ continue
800
+ title = re.sub(r"^Акція:\s*(?:\d+\s*днів?,?\s*)?\d{1,2}:\d{2}:\d{2}\s*", "",
801
+ link.get_text(" ", strip=True)).strip()
802
+ if not title:
803
+ continue
804
+ href = link.get("href") or ""
805
+ url = href if href.startswith("http") else f"https://kasta.ua{href}"
806
+ offer_id = _int_from(url.split("/product/")[-1].split(":")[0]) if "/product/" in url else None
807
+ if offer_id is None:
808
+ continue
809
+ _remember("kasta", offer_id, url)
810
+ row = {
811
+ "id": offer_id,
812
+ "title": title,
813
+ "price": _price_from_text((card.select_one(".t-18") or card).get_text()
814
+ if card.select_one(".t-18") else None),
815
+ "currency": "UAH",
816
+ "state": None,
817
+ "availability": None,
818
+ "city": None,
819
+ "business": True,
820
+ "relevance": _relevance(query, title),
821
+ }
822
+ old_el = card.select_one(".t-striked")
823
+ if old_el is not None:
824
+ row["old_price"] = _price_from_text(old_el.get_text())
825
+ rev_el = card.select_one("a[href*='#reviews']")
826
+ if rev_el is not None:
827
+ count = _int_from(rev_el.get_text(strip=True))
828
+ if count is not None:
829
+ row["reviews_count"] = count
830
+ rows.append(row)
831
+
832
+ return rows[: max(limit * 2, 20)]
833
+
834
+
835
+ async def kasta_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
836
+ return await _product_page(offer_id, "kasta", max_description_chars,
837
+ title_sel="h1",
838
+ price_sel=".t-18, [class*='price']",
839
+ desc_sel="[class*='description'], [itemprop='description']")
840
+
841
+
842
+ # --------------------------------------------------------------------------
843
+ # Brain — electronics, HTML + chrome (plain serves the same pages, slower)
844
+ # --------------------------------------------------------------------------
845
+
846
+ BRAIN_SEARCH = "https://brain.com.ua/ukr/search/"
847
+
848
+
849
+ async def brain_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
850
+ params: dict[str, Any] = {"Search": query}
851
+ if page > 1:
852
+ params["page"] = page
853
+ html = await _fetch(BRAIN_SEARCH, params, chrome=True)
854
+ soup = BeautifulSoup(html, "html.parser")
855
+ rows: list[dict[str, Any]] = []
856
+
857
+ for card in soup.select(".goods-block__item"):
858
+ add = card.select_one("a.add")
859
+ price_el = card.select_one(".br-pp-price")
860
+ url = next((a.get("href") for a in card.select("a[href]")
861
+ if "-p" in (a.get("href") or "") and (a.get("href") or "").endswith(".html")), None)
862
+ if url is None:
863
+ continue
864
+ offer_id = _int_from(add.get("data-pid") if add else None)
865
+ if offer_id is None:
866
+ offer_id = _int_from(url.rsplit("-p", 1)[-1])
867
+ if offer_id is None:
868
+ continue
869
+
870
+ title = (add.get("data-name-ua") or add.get("data-name")) if add else None
871
+ if not title:
872
+ img = card.select_one("img[alt]")
873
+ title = img.get("alt") if img is not None else ""
874
+ title = (title or "").strip()
875
+ if not title:
876
+ continue
877
+
878
+ price = _int_from(add.get("data-price") if add else None)
879
+ if price is None and price_el is not None:
880
+ for span in price_el.select("span"):
881
+ if "data_io" in (span.get("class") or []):
882
+ continue # service price in dollars / per unit
883
+ price = _int_from(span.get_text(strip=True))
884
+ if price is not None:
885
+ break
886
+
887
+ _remember("brain", offer_id, url)
888
+ row = {
889
+ "id": offer_id,
890
+ "title": title,
891
+ "price": price,
892
+ "currency": "UAH",
893
+ "state": None,
894
+ "availability": None,
895
+ "city": None,
896
+ "business": True,
897
+ "relevance": _relevance(query, title),
898
+ }
899
+ # Brain keeps the rating in ".br-pp-r": star images plus a number.
900
+ # 0.0 means "no reviews", such a rating is not returned.
901
+ r_el = card.select_one(".br-pp-r")
902
+ if r_el is not None:
903
+ spans = r_el.select("span")
904
+ rating_text = spans[-1].get_text(strip=True) if spans else ""
905
+ try:
906
+ rating = float(rating_text.replace(",", "."))
907
+ except ValueError:
908
+ rating = 0.0
909
+ if rating > 0:
910
+ row["rating"] = round(rating, 2)
911
+ rows.append(row)
912
+
913
+ return rows[: max(limit * 2, 20)]
914
+
915
+
916
+ async def brain_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
917
+ return await _product_page(offer_id, "brain", max_description_chars,
918
+ title_sel="h1",
919
+ price_sel=".br-pp-price [itemprop='price'], .br-main-price, "
920
+ ".br-pp-price span, [itemprop='price']",
921
+ desc_sel=".br-characteristics, .product-description, "
922
+ "[itemprop='description']")
923
+
924
+
925
+ # --------------------------------------------------------------------------
926
+ # Citrus (ctrs.com.ua) — electronics, Next.js HTML
927
+ # --------------------------------------------------------------------------
928
+
929
+ CTRS_SEARCH = "https://ctrs.com.ua/search"
930
+ _CTRS_ID_RE = re.compile(r"-(\d{4,})\.html$")
931
+ _CTRS_STAR_GREY = "221, 221, 221"
932
+
933
+
934
+ async def ctrs_search(query: str, limit: int = 10, page: int = 1) -> list[dict[str, Any]]:
935
+ params: dict[str, Any] = {"query": query}
936
+ if page > 1:
937
+ params["page"] = page
938
+ html = await _fetch(CTRS_SEARCH, params, chrome=True)
939
+ soup = BeautifulSoup(html, "html.parser")
940
+ rows: list[dict[str, Any]] = []
941
+
942
+ for card in soup.select("[class*='MainProductCard-module__root']"):
943
+ link = card.select_one("a[href]")
944
+ if link is None:
945
+ continue
946
+ href = link.get("href") or ""
947
+ m = _CTRS_ID_RE.search(href)
948
+ if not m:
949
+ continue
950
+ offer_id = int(m.group(1))
951
+ title_el = card.select_one("[class*='MainProductCard-module__title']")
952
+ title = (title_el.get_text(" ", strip=True) if title_el else "") or link.get("title", "")
953
+ title = (title or "").strip()
954
+ if not title:
955
+ continue
956
+
957
+ url = href if href.startswith("http") else f"https://ctrs.com.ua{href}"
958
+ price_el = card.select_one("[data-price]")
959
+ price = _int_from(price_el.get("data-price") if price_el is not None else None)
960
+ _remember("ctrs", offer_id, url)
961
+ row = {
962
+ "id": offer_id,
963
+ "title": title,
964
+ "price": price,
965
+ "currency": "UAH",
966
+ "state": None,
967
+ "availability": None,
968
+ "city": None,
969
+ "business": True,
970
+ "relevance": _relevance(query, title),
971
+ }
972
+ old_el = card.select_one("[data-old-price]")
973
+ if old_el is not None:
974
+ old_price = _int_from(old_el.get("data-old-price"))
975
+ if old_price:
976
+ row["old_price"] = old_price
977
+
978
+ # Citrus draws the rating as SVG stars without a number: count filled ones.
979
+ rating_root = card.select_one("[class*='Rating-module__root']")
980
+ if rating_root is not None:
981
+ fills = re.findall(r'fill="rgb\(([^)]*)\)"', str(rating_root))
982
+ filled = sum(1 for f in fills if f.strip() != _CTRS_STAR_GREY)
983
+ if filled:
984
+ row["rating"] = float(filled)
985
+ rows.append(row)
986
+
987
+ return rows[: max(limit * 2, 20)]
988
+
989
+
990
+ async def ctrs_get(offer_id: int, max_description_chars: int = 600) -> dict[str, Any]:
991
+ return await _product_page(offer_id, "ctrs", max_description_chars,
992
+ title_sel="h1",
993
+ price_sel="[data-price], .price, [itemprop='price']",
994
+ desc_sel="[class*='description'], [itemprop='description']")
995
+
996
+
997
+ async def _product_page(offer_id: int, source: str, max_description_chars: int, *,
998
+ title_sel: str, price_sel: str, desc_sel: str) -> dict[str, Any]:
999
+ """Shared product-card parser for the newer shops."""
1000
+ url = _fetch_url(source, int(offer_id))
1001
+ try:
1002
+ html = await _fetch(url, chrome=True)
1003
+ except OlxError as exc:
1004
+ if exc.code != "blocked":
1005
+ raise
1006
+ # Shops throttle frequent requests: a pause and one retry is enough.
1007
+ await asyncio.sleep(2.5)
1008
+ html = await _fetch(url, chrome=True)
1009
+ soup = BeautifulSoup(html, "html.parser")
1010
+
1011
+ title_el = soup.select_one(title_sel)
1012
+ title = title_el.get_text(strip=True) if title_el else None
1013
+
1014
+ price = None
1015
+ for sel in price_sel.split(","):
1016
+ el = soup.select_one(sel.strip())
1017
+ if el is None:
1018
+ continue
1019
+ price = _price_from_text(el.get("content") or el.get_text(" ", strip=True))
1020
+ if price is not None:
1021
+ break
1022
+
1023
+ desc_el = soup.select_one(desc_sel)
1024
+ description = desc_el.get_text(" ", strip=True) if desc_el else ""
1025
+ if max_description_chars and len(description) > max_description_chars:
1026
+ description = description[:max_description_chars].rstrip() + "…"
1027
+
1028
+ cached = _cached_row(source, int(offer_id))
1029
+ result: dict[str, Any] = {
1030
+ "source": source,
1031
+ "id": int(offer_id),
1032
+ "title": title or cached.get("title"),
1033
+ "price": price if price is not None else cached.get("price"),
1034
+ "currency": "UAH",
1035
+ "description": description,
1036
+ "url": url,
1037
+ }
1038
+ if price is None and cached.get("price") is not None:
1039
+ result["price_source"] = "search_card"
1040
+ if cached.get("old_price") is not None:
1041
+ result["old_price"] = cached["old_price"]
1042
+ if cached.get("rating") is not None:
1043
+ result.setdefault("rating", cached["rating"])
1044
+ if cached.get("reviews_count") is not None:
1045
+ result.setdefault("reviews_count", cached["reviews_count"])
1046
+ result.update(details.enrich(html, details.SHOPS.get(source), soup=soup))
1047
+ # The search rating is more precise: shops like Brain draw star images
1048
+ # and round 3.5 up to 4.0 on the card. So the search value wins and the
1049
+ # page value is kept in *_from_page.
1050
+ cached_rating = cached.get("rating")
1051
+ if cached_rating is not None:
1052
+ reviews = result.get("reviews") or {}
1053
+ if reviews.get("rating") is not None and reviews["rating"] != cached_rating:
1054
+ reviews["rating_from_page"] = reviews["rating"]
1055
+ reviews["rating"] = cached_rating
1056
+ reviews.setdefault("count", cached.get("reviews_count"))
1057
+ reviews.setdefault("items", [])
1058
+ reviews.setdefault("source", "search_card")
1059
+ result["reviews"] = reviews
1060
+ if "reviews" not in result and (cached.get("rating") is not None
1061
+ or cached.get("reviews_count") is not None):
1062
+ result["reviews"] = {"rating": cached.get("rating"),
1063
+ "count": cached.get("reviews_count"),
1064
+ "items": [], "source": "search_card"}
1065
+ return result
1066
+
1067
+ # --------------------------------------------------------------------------
1068
+ # Generic wrappers
1069
+ # --------------------------------------------------------------------------
1070
+
1071
+ SEARCHERS = {
1072
+ "prom": prom_search,
1073
+ "foxtrot": foxtrot_search,
1074
+ "rozetka": rozetka_search,
1075
+ "comfy": comfy_search,
1076
+ "allo": allo_search,
1077
+ "moyo": moyo_search,
1078
+ "kasta": kasta_search,
1079
+ "brain": brain_search,
1080
+ "ctrs": ctrs_search,
1081
+ }
1082
+
1083
+
1084
+ async def market_search(source: str, query: str, *, limit: int = 10, page: int = 1,
1085
+ price_min: int | None = None, price_max: int | None = None,
1086
+ sort: str | None = None, strict: bool = False,
1087
+ include_urls: bool = False) -> dict[str, Any]:
1088
+ searcher = SEARCHERS.get(source)
1089
+ if searcher is None:
1090
+ raise OlxError("bad_argument", f"source must be one of: {', '.join(SEARCHERS)}")
1091
+ page = max(1, int(page))
1092
+ limit = max(1, min(int(limit), 50))
1093
+
1094
+ rows = await searcher(query, limit=limit, page=page)
1095
+ return _finish(rows, total=len(rows), page=page, limit=limit,
1096
+ price_min=price_min, price_max=price_max, sort=sort,
1097
+ strict=strict, query=query, source=source,
1098
+ include_urls=include_urls)
1099
+
1100
+
1101
+ GETTERS = {
1102
+ "prom": prom_get,
1103
+ "foxtrot": foxtrot_get,
1104
+ "rozetka": rozetka_get,
1105
+ "comfy": comfy_get,
1106
+ "allo": allo_get,
1107
+ "moyo": moyo_get,
1108
+ "kasta": kasta_get,
1109
+ "brain": brain_get,
1110
+ "ctrs": ctrs_get,
1111
+ }
1112
+
1113
+
1114
+ async def market_get(source: str, offer_id: int, *,
1115
+ max_description_chars: int = 600) -> dict[str, Any]:
1116
+ getter = GETTERS.get(source)
1117
+ if getter is None:
1118
+ raise OlxError("bad_argument",
1119
+ f"source must be one of: {', '.join(GETTERS)}")
1120
+ if source == "rozetka":
1121
+ return await getter(int(offer_id))
1122
+ return await getter(int(offer_id), max_description_chars)