Repository navigation
Expand file tree
/
Copy pathscraper.py
More file actions
executable file
·1655 lines (1378 loc) · 57.4 KB
/
Copy pathscraper.py
File metadata and controls
executable file
·1655 lines (1378 loc) · 57.4 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import concurrent.futures
import logging
import random
import re
import sys
import threading
import time
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urljoin
import pandas as pd
import requests
from bs4 import BeautifulSoup
from rich.console import Console
from rich.logging import RichHandler
from rich.table import Table
from config import Config, load_config
from email_sender import send_email
from mysql_store import MySQLStore
from sheets import SheetsClient, normalise_phone
from utils import extract_email, extract_names, extract_phone_numbers, looks_like_person_name
# ---------------------------------------------------------------------------
# Logging setup
# ---------------------------------------------------------------------------
console = Console()
def _setup_logging(config: Config) -> None:
"""Configure the root logger with Rich (coloured) output + optional file."""
handlers: list[logging.Handler] = [
RichHandler(
console=console,
rich_tracebacks=True,
markup=True,
show_path=False,
)
]
if config.log_file:
file_handler = logging.FileHandler(config.log_file, encoding="utf-8")
file_handler.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)s — %(message)s")
)
handlers.append(file_handler)
logging.basicConfig(
level=getattr(logging, config.log_level, logging.INFO),
handlers=handlers,
format="%(message)s",
datefmt="[%X]",
)
logger = logging.getLogger("imoti_scraper")
def _ensure_utf8_stdio() -> None:
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)
if hasattr(stream, "reconfigure"):
try:
stream.reconfigure(encoding="utf-8", errors="replace")
except Exception: # noqa: BLE001
pass
# ---------------------------------------------------------------------------
# Data models
# ---------------------------------------------------------------------------
APARTMENT_KEYWORDS = (
"апартамент",
"едностаен",
"двустаен",
"тристаен",
"четиристаен",
"многостаен",
)
@dataclass
class Listing:
ad_id: str
title: str
price: str
location: str
size: str
link: str
# Populated during enrichment (detail page visit or list page extraction):
phone: str = ""
seller_name: str = "" # e.g. "Частно лице" or "Агенция XYZ"
ad_type: str = "" # "приватний" | "від агенції"
contact_name: str = "-"
contact_email: str = "-"
def as_row(self, today: str) -> list[str]:
return [
today,
self.ad_id,
self.title,
self.price,
self.location,
self.size,
self.link,
self.phone,
self.seller_name,
self.ad_type,
self.contact_name or "-",
self.contact_email or "-",
]
def as_dict(self) -> dict[str, str]:
"""Return a dict keyed by Config.new_ads_headers for the email template."""
return {
"Date": "",
"Ad_ID": self.ad_id,
"Title": self.title,
"Price": self.price,
"Location": self.location,
"Size": self.size,
"Link": self.link,
"Phone": self.phone,
"Seller_Name": self.seller_name,
"Type": self.ad_type,
"Contact_Name": self.contact_name or "-",
"Contact_Email": self.contact_email or "-",
}
@dataclass
class AgencyRecord:
agency_name: str
phones: list[str]
city: str = ""
email: str = ""
contact_name: str = ""
detail_url: str = ""
def to_dict(self) -> dict[str, str]:
return {
"Agency_Name": self.agency_name,
"Phones": ",".join(self.phones),
"City": self.city,
"Email": self.email,
"Contact_Name": self.contact_name,
}
@dataclass
class DetailPageInfo:
phone: str = ""
seller_name: str = ""
contact_name: str = "-"
contact_email: str = "-"
agency_profile_url: str = ""
@dataclass
class ParserRunResult:
exit_code: int
today: str
total_scraped: int = 0
new_count: int = 0
new_listings: list[Listing] | None = None
message: str = ""
# ---------------------------------------------------------------------------
# HTTP session factory — with User-Agent rotation
# ---------------------------------------------------------------------------
def _make_session(config: Config) -> requests.Session:
ua = random.choice(config.user_agents)
logger.debug("Using User-Agent: %s", ua)
session = requests.Session()
session.headers.update(
{
"User-Agent": ua,
"Accept": (
"text/html,application/xhtml+xml,application/xml;"
"q=0.9,image/avif,image/webp,*/*;q=0.8"
),
"Accept-Language": "bg-BG,bg;q=0.9,en-US;q=0.8,en;q=0.7",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
# Referrer to mimic a real browser navigation.
"Referer": "https://imoti.bg/",
}
)
return session
def _polite_get(
session: requests.Session,
url: str,
config: Config,
retries: int = 3,
backoff: float = 5.0,
) -> Optional[requests.Response]:
delay = random.uniform(config.request_delay_min, config.request_delay_max)
logger.debug("Sleeping %.1f s before fetching %s", delay, url)
time.sleep(delay)
for attempt in range(1, retries + 1):
try:
resp = session.get(url, timeout=30)
resp.raise_for_status()
return resp
except requests.HTTPError as exc:
status = exc.response.status_code if exc.response is not None else "?"
logger.warning("HTTP %s for %s (attempt %d/%d)", status, url, attempt, retries)
except requests.RequestException as exc:
logger.warning("Request error for %s (attempt %d/%d): %s", url, attempt, retries, exc)
if attempt < retries:
wait = backoff * attempt
logger.debug("Waiting %.1f s before retry …", wait)
time.sleep(wait)
# Rotate User-Agent on retry.
session.headers["User-Agent"] = random.choice(config.user_agents)
logger.error("Giving up on %s after %d attempts.", url, retries)
return None
# ---------------------------------------------------------------------------
# Listing-page parser
# ---------------------------------------------------------------------------
_AD_ID_RE = re.compile(r"-(\d{4,10})\.htm$", re.IGNORECASE)
_PHONE_TEXT_RE = re.compile(
r"(?:тел\.?\s*:?\s*)?(\+?359[\s\-]?|0)(\d[\d\s\-]{6,12}\d)",
re.IGNORECASE,
)
_EMAIL_RE = re.compile(r"[\w.\-+]+@[\w.\-]+\.[a-z]{2,}", re.IGNORECASE)
_AGU_HREF_RE = re.compile(r"agu:\d+", re.IGNORECASE)
CONTACT_SENTINEL = "-"
def _extract_ad_id(url: str) -> str:
match = _AD_ID_RE.search(url)
return match.group(1) if match else ""
def _is_apartment(title: str, url: str) -> bool:
combined = (title + " " + url).lower()
return any(kw in combined for kw in APARTMENT_KEYWORDS)
def _extract_phone_from_text(text: str) -> str:
"""Extract the first valid phone number from text using improved logic."""
if not text:
return ""
phones = extract_phone_numbers(text)
return phones[0] if phones else ""
def parse_listing_page(
html: str,
base_url: str,
city_filter: Optional[str] = None,
) -> list[Listing]:
soup = BeautifulSoup(html, "html.parser")
listings: list[Listing] = []
# Each listing card is wrapped in <article class="product-classic">
for article in soup.select("article.product-classic"):
try:
listing = _parse_card(article, base_url)
except Exception as exc: # noqa: BLE001
logger.debug("Skipping malformed card: %s", exc)
continue
if listing is None:
continue
# ── Filter: apartments only ──────────────────────────────────────
if not _is_apartment(listing.title, listing.link):
logger.debug("Skipping non-apartment: '%s'", listing.title)
continue
# ── Filter: optional city filter ─────────────────────────────────
if city_filter and city_filter.lower() not in listing.location.lower():
logger.debug(
"Skipping ad outside city filter ('%s'): %s",
city_filter,
listing.location,
)
continue
listings.append(listing)
return listings
def _parse_card(
article: BeautifulSoup,
base_url: str,
) -> Optional[Listing]:
# ── Link & Ad ID ─────────────────────────────────────────────────────
title_anchor = article.select_one("h4.product-classic-title a")
if not title_anchor:
return None
raw_href: str = title_anchor.get("href", "")
link = raw_href if raw_href.startswith("http") else urljoin(base_url, raw_href)
ad_id = _extract_ad_id(link)
if not ad_id:
return None
# ── Title ─────────────────────────────────────────────────────────────
title = title_anchor.get_text(strip=True)
# ── Price ─────────────────────────────────────────────────────────────
price_el = article.select_one(".product-classic-price")
if price_el:
price_lines = [ln.strip() for ln in price_el.get_text("\n").splitlines() if ln.strip()]
price = price_lines[0] if price_lines else ""
else:
price = ""
# ── Location ──────────────────────────────────────────────────────────
location_el = article.select_one(".btext")
location = location_el.get_text(strip=True) if location_el else ""
# ── Size ──────────────────────────────────────────────────────────────
size = ""
for li in article.select(".product-classic-list li"):
text = li.get_text(strip=True)
if "кв.м." in text:
size = text
break
# ── Phone (opportunistic from card) ───────────────────────────────────
phone = _extract_phone_from_card(article)
# ── Seller Name (opportunistic from card) ─────────────────────────────
seller_name = _extract_seller_name_from_card(article)
return Listing(
ad_id=ad_id,
title=title,
price=price,
location=location,
size=size,
link=link,
phone=phone,
seller_name=seller_name,
)
def _extract_phone_from_card(article: BeautifulSoup) -> str:
# 1. href="tel:..." anchor
tel_link = article.select_one('a[href^="tel:"]')
if tel_link:
raw = tel_link.get("href", "").replace("tel:", "")
phone = _extract_phone_from_text(raw)
if phone:
return phone
# 2. Elements with phone-related class names
for selector in (
"[class*='phone']",
"[class*='tel']",
".contact-phone",
".phone-number",
"span.phone",
):
el = article.select_one(selector)
if el:
phones = extract_phone_numbers(el.get_text(strip=True))
if phones:
return phones[0]
# 3. Text scan for "Тел" prefix in the full card text
full_text = article.get_text(" ", strip=True)
phone = _extract_phone_from_text(full_text)
if phone:
return phone
return ""
def _extract_seller_name_from_card(article: BeautifulSoup) -> str:
# Try several common CSS patterns for the seller block on listing cards.
for selector in (
".product-classic-agency",
".agency-name",
".seller-name",
"[class*='agency']",
"[class*='seller']",
".block-info h3", # may appear in card previews
):
el = article.select_one(selector)
if el:
name = el.get_text(strip=True)
if name:
# Check if the name looks like a person's name
if looks_like_person_name(name):
return name
# If it doesn't look like a person's name, return as seller name
return name
# If no specific selector found, try to extract from the full article
text_content = article.get_text(" ", strip=True)
names = extract_names(text_content)
if names:
return names[0]
return ""
def parse_detail_page(html: str, url: str = "") -> DetailPageInfo:
soup = BeautifulSoup(html, "html.parser")
info = DetailPageInfo()
# ── Seller name from page title or header ─────────────────────────────
for sel in (
"h1 a",
".product-title a",
".property-title",
"[class*='owner']",
"[class*='seller']",
"[class*='agency']",
):
el = soup.select_one(sel)
if el:
info.seller_name = el.get_text(strip=True)
if info.seller_name:
break
if not info.seller_name:
title_tag = soup.select_one("title")
if title_tag:
# Extract seller from title like "Продава двустаен апартамент в Студентски | Частно лице"
title_text = title_tag.get_text()
if "|" in title_text:
potential_seller = title_text.split("|")[-1].strip()
if looks_like_person_name(potential_seller):
info.seller_name = potential_seller
# ── Phone number extraction ────────────────────────────────────────────
# First, try to extract from structured elements
for sel in (
".phone-number",
".contact-phone",
"[class*='phone']",
"[class*='tel']",
):
el = soup.select_one(sel)
if el:
phones = extract_phone_numbers(el.get_text(strip=True))
if phones:
info.phone = phones[0]
break
# If not found in structured elements, search in all text
if not info.phone:
all_text = soup.get_text(" ", strip=True)
phones = extract_phone_numbers(all_text)
if phones:
info.phone = phones[0]
# ── Contact name/email from card blocks ───────────────────────────────
info.contact_name = _extract_contact_name_from_detail_soup(soup)
info.contact_email = _extract_contact_email_from_detail_soup(soup)
info.agency_profile_url = _extract_agency_profile_url_from_detail_soup(soup)
return info
def _extract_contact_name_from_detail_soup(soup: BeautifulSoup) -> str:
blocks = soup.select("div.block-person-link")
for block in blocks:
# First non-mailto/non-tel anchor often contains profile owner name.
for a_tag in block.find_all("a", href=True):
href = a_tag.get("href", "").lower()
if href.startswith(("mailto:", "tel:")):
continue
if _AGU_HREF_RE.search(href):
continue
candidate = a_tag.get_text(" ", strip=True)
if looks_like_person_name(candidate):
return candidate
# Fallback tags inside block.
for tag in block.find_all(["span", "strong", "b", "p", "div"]):
candidate = tag.get_text(" ", strip=True)
if looks_like_person_name(candidate):
return candidate
# Last resort: use block text stripped from phone/email.
text = block.get_text(" ", strip=True)
text = _EMAIL_RE.sub("", text)
text = _PHONE_TEXT_RE.sub("", text)
text = text.strip(" @,;:|–-")
if looks_like_person_name(text):
return text
# Secondary generic selectors.
for sel in (
".contact-name",
".agent-name",
".block-agent-contact .name",
".contact-person",
"[class*='contact-name']",
):
el = soup.select_one(sel)
if not el:
continue
candidate = el.get_text(" ", strip=True)
if looks_like_person_name(candidate):
return candidate
return "-"
def _extract_contact_email_from_detail_soup(soup: BeautifulSoup) -> str:
# 1) Prefer mailto inside person/contact blocks.
for root in soup.select("div.block-person-link, div.block-info, div.block-agent"):
mail = root.select_one('a[href^="mailto:"]')
if mail:
email = mail.get("href", "").replace("mailto:", "").split("?")[0].strip()
if email:
return email
txt = root.get_text(" ", strip=True)
matches = extract_email(txt)
if matches:
return matches[0]
# 2) Any mailto on the page.
mail = soup.select_one('a[href^="mailto:"]')
if mail:
email = mail.get("href", "").replace("mailto:", "").split("?")[0].strip()
if email:
return email
# 3) Regex fallback over visible text.
for container in ("main", "#main", ".main-content", ".content", "article", "body"):
el = soup.select_one(container)
if not el:
continue
matches = extract_email(el.get_text(" ", strip=True))
if matches:
return matches[0]
return "-"
def _extract_agency_profile_url_from_detail_soup(soup: BeautifulSoup) -> str:
for root in soup.select("div.block-info, div.block-agent, body"):
for a_tag in root.select("a[href]"):
href = a_tag.get("href", "").strip()
if not href or not _AGU_HREF_RE.search(href):
continue
return href if href.startswith("http") else urljoin("https://imoti.bg/", href)
return ""
def _looks_like_person_name(text: str) -> bool:
"""Use improved name validation from utils module."""
return looks_like_person_name(text)
# ---------------------------------------------------------------------------
# Pagination helper
# ---------------------------------------------------------------------------
def _has_next_page(soup: BeautifulSoup) -> bool:
# First, check for common pagination patterns in text
for a in soup.select("ul.pagination a, .pagination a, a.next, li.next a"):
text = a.get_text(strip=True).lower()
if "»" in a.get_text() or text in ("следваща", "next", ">"):
return True
# Also check for any link with page:N pattern (more reliable)
for a in soup.select("a[href*='/page:']"):
href = a.get("href", "")
# If there's a link to a higher page number, we have pagination
if "/page:" in href:
# Check if it's not just linking to current page
# Look for > or » symbols
text = a.get_text(strip=True)
if ">" in text or "»" in text or text == ">":
return True
return False
# ---------------------------------------------------------------------------
# Core scraping logic — listing pages
# ---------------------------------------------------------------------------
def scrape_all_pages(
session: requests.Session,
config: Config,
) -> list[Listing]:
all_listings: list[Listing] = []
seen_ids: set[str] = set() # dedup within a single scrape run
for page_num in range(1, config.max_pages + 1):
url = config.base_url.format(page=page_num)
logger.info("Scraping listing page %d → %s", page_num, url)
resp = _polite_get(session, url, config)
if not resp:
logger.error("Failed to fetch page %d", page_num)
continue
try:
listings = parse_listing_page(resp.text, url, config.city_filter)
except Exception as exc: # noqa: BLE001
logger.error("Failed to parse page %d: %s", page_num, exc)
continue
new_on_page = 0
for listing in listings:
if listing.ad_id not in seen_ids:
all_listings.append(listing)
seen_ids.add(listing.ad_id)
new_on_page += 1
logger.info(
"Found %d new listings on page %d (total so far: %d)",
new_on_page,
page_num,
len(all_listings),
)
if not _has_next_page(BeautifulSoup(resp.text, "html.parser")):
logger.info("No more pages detected, stopping early.")
break
return all_listings
def _resolve_agency_contact_key(
listing: Listing,
agency_phones: set[str],
agency_names: set[str],
) -> Optional[tuple[str, str]]:
"""
Resolve if a listing belongs to an agency based on phone or name match.
Returns:
(agency_phone, agency_name) tuple if match found, None otherwise
"""
if not listing.phone and not listing.seller_name:
return None
# Match by phone
if listing.phone in agency_phones:
return (listing.phone, "")
# Match by name
if listing.seller_name and listing.seller_name in agency_names:
return ("", listing.seller_name)
return None
class ContactResolver:
"""Resolve listing contacts using sheet cache, detail page and agency profile."""
def __init__(
self,
session: requests.Session,
config: Config,
agency_contacts: dict[str, dict[str, str]],
) -> None:
self._session = session
self._config = config
self._agency_contacts_source = agency_contacts
self._detail_cache: dict[str, DetailPageInfo] = {}
self._agency_cache: dict[str, dict[str, str]] = {}
self._agu_cache: dict[str, dict[str, str]] = {}
def get_listing_detail(self, listing: Listing) -> DetailPageInfo:
key = listing.ad_id or listing.link
if key in self._detail_cache:
return self._detail_cache[key]
resp = _polite_get(self._session, listing.link, self._config)
if resp is None:
info = DetailPageInfo()
else:
info = parse_detail_page(resp.text, listing.link)
self._detail_cache[key] = info
return info
def resolve_from_agency_sheet(self, seller_name: str) -> dict[str, str]:
seller_name_lower = (seller_name or "").strip().lower()
if not seller_name_lower:
return {"contact_name": CONTACT_SENTINEL, "contact_email": CONTACT_SENTINEL}
if seller_name_lower in self._agency_cache:
return self._agency_cache[seller_name_lower]
key = _resolve_agency_contact_key(seller_name_lower, self._agency_contacts_source)
if not key:
info = {"contact_name": CONTACT_SENTINEL, "contact_email": CONTACT_SENTINEL}
self._agency_cache[seller_name_lower] = info
return info
row = self._agency_contacts_source.get(key, {})
info = {
"contact_name": (row.get("contact_name", "").strip() or CONTACT_SENTINEL),
"contact_email": (row.get("contact_email", "").strip() or CONTACT_SENTINEL),
}
self._agency_cache[seller_name_lower] = info
return info
def resolve_from_agency_profile(self, profile_url: str) -> dict[str, str]:
if not profile_url:
return {"contact_name": CONTACT_SENTINEL, "contact_email": CONTACT_SENTINEL}
key = profile_url.strip()
if key in self._agu_cache:
return self._agu_cache[key]
details = parse_agency_details(profile_url, self._session, self._config)
info = {
"contact_name": details.get("contact_name", "").strip() or CONTACT_SENTINEL,
"contact_email": details.get("email", "").strip() or CONTACT_SENTINEL,
}
self._agu_cache[key] = info
return info
def enrich_listing(
listing: Listing,
agency_phones: set[str],
agency_names: set[str],
contact_resolver: ContactResolver,
) -> None:
detail_info: Optional[DetailPageInfo] = None
def ensure_detail() -> DetailPageInfo:
nonlocal detail_info
if detail_info is None:
logger.debug(
"Fetching detail page for ad %s (phone=%r, seller=%r)",
listing.ad_id,
listing.phone,
listing.seller_name,
)
detail_info = contact_resolver.get_listing_detail(listing)
return detail_info
# Fill core fields first (needed for classification).
if not listing.phone or not listing.seller_name:
detail = ensure_detail()
if not listing.phone and detail.phone:
listing.phone = detail.phone
if not listing.seller_name and detail.seller_name:
listing.seller_name = detail.seller_name
if not listing.phone and not listing.seller_name:
logger.warning(
"Ad %s: could not find phone or seller name on list page or detail page.",
listing.ad_id,
)
listing.ad_type = _classify_listing(
phone=listing.phone,
seller_name=listing.seller_name,
agency_phones=agency_phones,
agency_names=agency_names,
)
if listing.ad_type == "частно лице":
detail = ensure_detail()
listing.contact_name = detail.contact_name or CONTACT_SENTINEL
listing.contact_email = detail.contact_email or CONTACT_SENTINEL
else:
sheet_contact = contact_resolver.resolve_from_agency_sheet(listing.seller_name)
name = sheet_contact["contact_name"]
email = sheet_contact["contact_email"]
if name == CONTACT_SENTINEL or email == CONTACT_SENTINEL:
detail = ensure_detail()
if name == CONTACT_SENTINEL and detail.contact_name != CONTACT_SENTINEL:
name = detail.contact_name
if email == CONTACT_SENTINEL and detail.contact_email != CONTACT_SENTINEL:
email = detail.contact_email
if (
name == CONTACT_SENTINEL or email == CONTACT_SENTINEL
) and detail.agency_profile_url:
profile_contact = contact_resolver.resolve_from_agency_profile(
detail.agency_profile_url
)
if name == CONTACT_SENTINEL and profile_contact["contact_name"] != CONTACT_SENTINEL:
name = profile_contact["contact_name"]
if (
email == CONTACT_SENTINEL
and profile_contact["contact_email"] != CONTACT_SENTINEL
):
email = profile_contact["contact_email"]
listing.contact_name = name or CONTACT_SENTINEL
listing.contact_email = email or CONTACT_SENTINEL
logger.debug(
" Ad %s → phone=%s, seller=%r, type=%s, contact=%r, email=%r",
listing.ad_id,
listing.phone,
listing.seller_name,
listing.ad_type,
listing.contact_name,
listing.contact_email,
)
def _classify_listing(
phone: str,
seller_name: str,
agency_phones: set[str],
agency_names: set[str],
) -> str:
# 1. Phone in agency phone set.
if phone and phone in agency_phones:
return "от агенция"
# 2. Seller name contains any agency name substring.
if seller_name:
seller_lower = seller_name.lower()
for agency_name in agency_names:
if agency_name and agency_name in seller_lower:
return "от агенция"
return "частно лице"
# ---------------------------------------------------------------------------
# Agency scraping
# ---------------------------------------------------------------------------
def scrape_agencies(
session: requests.Session,
config: Config,
) -> list[AgencyRecord]:
all_agencies: list[AgencyRecord] = []
seen_agencies: set[str] = set()
for page_num in range(1, config.max_agency_pages + 1):
url = config.agencies_url.format(page=page_num)
logger.info("Scraping agencies page %d → %s", page_num, url)
resp = _polite_get(session, url, config)
if not resp:
logger.error("Failed to fetch agencies page %d", page_num)
continue
try:
agencies = _parse_agency_page(resp.text, url)
except Exception as exc: # noqa: BLE001
logger.error("Failed to parse agencies page %d: %s", page_num, exc)
continue
new_on_page = 0
for agency in agencies:
# Use agency name and primary phone as unique identifier
unique_id = (agency.agency_name or "").lower()
if agency.phones:
unique_id += "_" + agency.phones[0]
if unique_id not in seen_agencies:
all_agencies.append(agency)
seen_agencies.add(unique_id)
new_on_page += 1
logger.info(
"Found %d new agencies on page %d (total so far: %d)",
new_on_page,
page_num,
len(all_agencies),
)
soup = BeautifulSoup(resp.text, "html.parser")
if not _has_next_page(soup):
logger.info("No more agency pages detected, stopping early.")
break
return all_agencies
def _parse_agency_page(html: str, base_url: str) -> list[AgencyRecord]:
soup = BeautifulSoup(html, "html.parser")
agencies: list[AgencyRecord] = []
# Find agency containers - typically in grid or list format
for container in soup.select("article.product-classic, .agency-item, .agency-card"):
agency = _parse_agency_container(container, base_url)
if agency:
agencies.append(agency)
return agencies
def _parse_agency_container(container: BeautifulSoup, base_url: str) -> Optional[AgencyRecord]:
try:
# Agency name
name_selector = (".agency-name", ".product-classic-title a", "h3", "[class*='title']")
agency_name = ""
for sel in name_selector:
el = container.select_one(sel)
if el:
agency_name = el.get_text(strip=True)
break
if not agency_name:
return None
# Agency detail URL
detail_url = ""
link_el = container.select_one("a[href]")
if link_el:
href = link_el.get("href", "")
detail_url = href if href.startswith("http") else urljoin(base_url, href)
# Extract contact information
agency_data = parse_agency_details(detail_url) if detail_url else {}
# Fallback to extracting from container if no detail page was fetched
if not agency_data.get("phones"):
# Extract phones from the listing container
phones = []
phone_elements = container.select("[class*='phone'], [class*='tel'], .contact-info")
for el in phone_elements:
phone_text = el.get_text(strip=True)
extracted_phones = extract_phone_numbers(phone_text)
phones.extend(extracted_phones)
agency_data["phones"] = list(set(phones)) # Remove duplicates
if not agency_data.get("contact_name"):
# Extract names from the container
text_content = container.get_text(" ", strip=True)
names = extract_names(text_content)
if names:
agency_data["contact_name"] = names[0]
if not agency_data.get("email"):
# Extract emails from the container
text_content = container.get_text(" ", strip=True)
emails = extract_email(text_content)
if emails:
agency_data["email"] = emails[0]
# City - might be in .btext or similar location indicator
city_el = container.select_one(".btext, .location, .city")
city = city_el.get_text(strip=True) if city_el else ""
return AgencyRecord(
agency_name=agency_name,
phones=agency_data.get("phones", []),
city=city,
email=agency_data.get("email", ""),
contact_name=agency_data.get("contact_name", ""),
detail_url=detail_url,
)
except Exception as e:
logger.debug("Error parsing agency container: %s", e)
return None