-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
1806 lines (1539 loc) · 70.3 KB
/
Copy pathscraper.py
File metadata and controls
1806 lines (1539 loc) · 70.3 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
"""
scraper.py — Ultimativer Lead-Scraper mit Base64-Fix, Deep-Scan & Multi-Tab
Features:
- Google Maps: Deep-Scan mit aria-label/authority Extraktion
- Gelbe Seiten: Base64-dekodierte data-webseitelink Attribute
- Das Örtliche: Direkte URL mit Paginierung
- Email-Extraktion: Startseite → Impressum → Kontakt (neuer Tab pro Website)
- Anti-Blocking: Cookie-Buster, Captcha-Pause, Tab-Close
- Variablen-Reset: Jede Iteration startet mit leeren Werten
- Telegram: Sofortige Nachricht pro Lead
- Notion-Sync über notion_db.py
"""
import asyncio
import base64
import csv
import json
import logging
import os
import random
import re
from datetime import datetime
from pathlib import Path
from typing import Callable, Optional
from urllib.parse import urljoin, urlparse, unquote
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright, Page, BrowserContext
from playwright_stealth.stealth import Stealth
logger = logging.getLogger("leadbot.scraper")
# ─── Pfade ───────────────────────────────────────────────────────────────────
BASE_DIR = Path(__file__).parent.resolve()
DB_PATH = BASE_DIR / "db" / "leads.json"
PROGRESS_PATH = BASE_DIR / "db" / "hunt_progress.json"
BACKUP_CSV_PATH = BASE_DIR / "backup_leads.csv"
SCREENSHOTS_DIR = BASE_DIR / "screenshots"
BROWSER_SESSION_DIR = BASE_DIR / "browser_session"
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
BROWSER_SESSION_DIR.mkdir(parents=True, exist_ok=True)
# ─── Datenbank ───────────────────────────────────────────────────────────────
from tinydb import TinyDB
db = TinyDB(str(DB_PATH))
LeadsTable = db.table("leads")
# ─── Branchen ────────────────────────────────────────────────────────────────
HUNT_BRANCHES = [
"dachdecker", "sanitär", "elektriker", "maler",
"tischler", "schreiner", "klempner", "fliesenleger",
"gärtner", "gartenbau", "zimmerer", "stuckateur",
"bodenleger", "glaserei", "metallbau", "trockenbau",
"gerüstbau", "heizungsbau", "solartechnik", "gaLaBau",
]
# ─── Globale Zustände ────────────────────────────────────────────────────────
browser_manager: Optional["BrowserManager"] = None
captcha_callback: Optional[Callable] = None
SEARCH_RADIUS_KM: int = 10
# ==============================================================================
# BrowserManager — Persistent Context + Stealth + Multi-Tab Support
# ==============================================================================
class BrowserManager:
def __init__(self, headless: bool = False):
self.playwright = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
self.headless = headless
async def launch(self):
logger.info(
"Starte Browser (headless=%s) mit persistentem Session-Store: %s",
self.headless, BROWSER_SESSION_DIR,
)
self.playwright = await async_playwright().start()
self.context = await self.playwright.chromium.launch_persistent_context(
user_data_dir=str(BROWSER_SESSION_DIR),
headless=self.headless,
viewport={"width": 1920, "height": 1080},
locale="de-DE",
user_agent=(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/131.0.0.0 Safari/537.36"
),
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-infobars",
"--disable-extensions",
"--disable-gpu",
],
)
self.page = await self.context.new_page()
await Stealth().apply_stealth_async(self.page)
logger.info("Browser gestartet")
async def new_tab(self) -> Page:
page = await self.context.new_page()
await Stealth().apply_stealth_async(page)
return page
async def close(self):
if self.context:
await self.context.close()
if self.playwright:
await self.playwright.stop()
self.page = None
self.context = None
logger.info("Browser geschlossen")
async def random_delay(self, min_sec: float = 2.0, max_sec: float = 5.0):
delay = random.uniform(min_sec, max_sec)
await asyncio.sleep(delay)
async def detect_captcha(self, page: Page) -> bool:
try:
captcha_selectors = [
"div.g-recaptcha",
"iframe[src*='recaptcha']",
"iframe[src*='google.com/recaptcha']",
"#recaptcha",
"div[class*='captcha']",
]
for selector in captcha_selectors:
if await page.query_selector(selector):
return True
title = (await page.title()).lower()
if "captcha" in title or "robot" in title:
return True
url = page.url.lower()
if any(p in url for p in ["sorry", "unusual traffic", "security check", "verify"]):
return True
body = (await page.text_content("body") or "").lower()
if any(p in body for p in ["prove you're not a robot", "roboter bestätigen", "ich bin kein robot"]):
return True
return False
except Exception:
return False
async def handle_captcha(self):
logger.warning("CAPTCHA erkannt")
if captcha_callback:
try:
result = captcha_callback("⚠️ CAPTCHA! Bitte am PC lösen.")
if asyncio.iscoroutine(result):
await result
except Exception:
pass
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None,
lambda: input("Drücke Enter im Terminal, wenn du das Captcha gelöst hast..."),
)
logger.info("Captcha gelöst — fahre fort")
async def handle_cookie_consent(self, page: Page):
try:
keywords = [
"Alle akzeptieren", "Ich stimme zu", "Accept all",
"Zustimmen", "Einverstanden", "OK", "Agree",
"akzeptieren", "accept", "consent", "zustimmen",
]
clicked_any = False
for keyword in keywords:
try:
buttons = await page.query_selector_all(
f'button:has-text("{keyword}"), '
f'a:has-text("{keyword}"), '
f'[role="button"]:has-text("{keyword}")'
)
for btn in buttons:
try:
if await btn.is_visible():
await btn.click()
clicked_any = True
await page.wait_for_timeout(800)
except Exception:
continue
except Exception:
continue
if clicked_any:
await page.wait_for_timeout(1000)
logger.info("Cookie-Banner geschlossen")
except Exception:
pass
async def scroll_sidebar(self, page: Page, sidebar_selector: str = "div[role='feed']", scrolls: int = 12, pause_ms: int = 800):
try:
sidebar = await page.query_selector(sidebar_selector)
if sidebar:
box = await sidebar.bounding_box()
if box:
await page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
await page.wait_for_timeout(300)
for i in range(scrolls):
await page.mouse.wheel(0, random.randint(300, 700))
jitter = random.randint(-200, 300)
await page.wait_for_timeout(pause_ms + jitter)
if (i + 1) % 4 == 0:
await page.mouse.wheel(0, -random.randint(50, 150))
await page.wait_for_timeout(random.randint(200, 500))
else:
await page.mouse.wheel(0, 600)
await page.wait_for_timeout(pause_ms)
except Exception:
pass
# ==============================================================================
# EMAIL-Extraktion — Website-Besuch + Impressum/Kontakt-Fallback
# ==============================================================================
_BAD_EMAIL_DOMAINS = frozenset([
"example.com", "test.com", "domain.com", "email.com",
"gmail.com", "yahoo.com", "hotmail.com", "outlook.com",
"web.de", "gmx.de", "gmx.net", "t-online.de",
])
_BAD_EMAIL_KEYWORDS = frozenset([
".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp",
"noreply", "no-reply", "info@", "kontakt@", "contact@",
"support@", "service@", "admin@", "webmaster@",
"postmaster@", "hostmaster@", "abuse@", "sales@",
"marketing@", "office@", "team@", "mail@",
"vertrieb@", "geschaeftsfuehrung@", "gf@",
])
def _is_valid_business_email(email: str) -> bool:
email_lower = email.lower().strip()
if any(bad in email_lower for bad in _BAD_EMAIL_KEYWORDS):
return False
domain = email_lower.split("@")[-1]
if domain in _BAD_EMAIL_DOMAINS:
return False
return True
def _extract_emails_from_text(text: str) -> list[str]:
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
found = re.findall(pattern, text)
cleaned = []
for e in found:
if any(e.lower().endswith(ext) for ext in ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp']):
continue
if 'cdn' in e.lower() or 'assets' in e.lower() or 'wp-content' in e.lower():
continue
cleaned.append(e)
return list(dict.fromkeys(cleaned))
async def extract_email_from_website(url: str) -> str:
"""
Besucht eine Website in einem neuen Tab und extrahiert E-Mails.
Schließt den Tab sofort nach dem Scan.
"""
if not url or not url.startswith("http"):
return ""
if not browser_manager or not browser_manager.context:
return ""
page = None
try:
page = await browser_manager.new_tab()
await browser_manager.random_delay(2, 3)
logger.info("[Email] Besuche: %s", url)
await page.goto(url, wait_until="domcontentloaded", timeout=15000)
await page.wait_for_timeout(2500)
# 1. Startseite
html = await page.content()
emails = _extract_emails_from_text(html)
business_emails = [e for e in emails if _is_valid_business_email(e)]
if business_emails:
logger.info("[Email] Startseite: %s", business_emails[0])
return business_emails[0]
if emails:
return emails[0]
# 2. Impressum
impressum_link = None
for a in await page.query_selector_all("a[href]"):
try:
text = (await a.inner_text()).strip().lower()
href = (await a.get_attribute("href")) or ""
if any(kw in text for kw in ["impressum", "imprint", "legal notice"]):
impressum_link = urljoin(url, href)
break
if any(kw in href.lower() for kw in ["impressum", "imprint"]):
impressum_link = urljoin(url, href)
break
except Exception:
continue
if impressum_link:
try:
logger.debug("[Email] Impressum: %s", impressum_link)
await page.goto(impressum_link, wait_until="domcontentloaded", timeout=10000)
await page.wait_for_timeout(1500)
html = await page.content()
emails = _extract_emails_from_text(html)
business_emails = [e for e in emails if _is_valid_business_email(e)]
if business_emails:
logger.info("[Email] Impressum: %s", business_emails[0])
return business_emails[0]
if emails:
return emails[0]
except Exception:
pass
# 3. Kontakt
try:
await page.goto(url, wait_until="domcontentloaded", timeout=10000)
await page.wait_for_timeout(1000)
except Exception:
pass
kontakt_link = None
for a in await page.query_selector_all("a[href]"):
try:
text = (await a.inner_text()).strip().lower()
href = (await a.get_attribute("href")) or ""
if any(kw in text for kw in ["kontakt", "contact", "anfrage"]):
kontakt_link = urljoin(url, href)
break
if any(kw in href.lower() for kw in ["kontakt", "contact"]):
kontakt_link = urljoin(url, href)
break
except Exception:
continue
if kontakt_link:
try:
logger.debug("[Email] Kontakt: %s", kontakt_link)
await page.goto(kontakt_link, wait_until="domcontentloaded", timeout=10000)
await page.wait_for_timeout(1500)
html = await page.content()
emails = _extract_emails_from_text(html)
business_emails = [e for e in emails if _is_valid_business_email(e)]
if business_emails:
logger.info("[Email] Kontakt: %s", business_emails[0])
return business_emails[0]
if emails:
return emails[0]
except Exception:
pass
logger.info("[Email] Keine E-Mail auf %s", url)
return ""
except Exception:
return ""
finally:
if page:
try:
await page.close()
logger.debug("[Email] Tab geschlossen")
except Exception:
pass
# ==============================================================================
# Google Maps Deep-Scan
# ==============================================================================
async def _find_maps_search_field(page: Page) -> Optional[object]:
selectors = [
"input#searchboxinput", "input.gsfi", 'textarea[name="q"]',
'input[name="q"]', "input[placeholder*='Suchen']",
"input[placeholder*='Search']", "input[aria-label*='Suchen']",
"input[aria-label*='Search']", "#searchbox input", ".searchbox input",
]
for selector in selectors:
try:
el = await page.query_selector(selector)
if el and await el.is_visible():
return el
except Exception:
continue
return None
async def scrape_google_maps(
branch: str, city: str, max_results: int = 20,
page: Page = None, radius_km: int = None,
) -> list[dict]:
if not browser_manager or not browser_manager.context:
return []
if page is None:
page = await browser_manager.new_tab()
if radius_km is None:
radius_km = SEARCH_RADIUS_KM
query = f"{branch} {city} + {radius_km}km"
logger.info("[Maps] Suche: %s (Radius: %dkm)", query, radius_km)
results = []
seen_names = set()
for attempt in range(1, 3):
try:
await browser_manager.random_delay(2, 5)
await page.goto("https://www.google.de/maps", wait_until="domcontentloaded", timeout=30000)
# Consent-Buster
for sel in [
'button:has-text("Alle akzeptieren")',
'button:has-text("Ich stimme zu")',
'button:has-text("Zustimmen")',
'button:has-text("Accept all")',
'a:has-text("Alle akzeptieren")',
'[role="button"]:has-text("Alle akzeptieren")',
'form button',
]:
try:
await page.click(sel, timeout=5000)
await page.wait_for_timeout(1200)
except Exception:
pass
await page.wait_for_timeout(1500)
if await browser_manager.detect_captcha(page):
await browser_manager.handle_captcha()
search_field = await _find_maps_search_field(page)
if not search_field:
if attempt == 1:
await page.wait_for_timeout(5000)
search_field = await _find_maps_search_field(page)
if not search_field:
error_path = str(SCREENSHOTS_DIR / "maps_error.png")
await page.screenshot(path=error_path, full_page=True)
logger.error("[Maps] Suchfeld nicht gefunden! Screenshot: %s", error_path)
return []
await search_field.click()
await page.wait_for_timeout(random.uniform(200, 500))
for _ in range(3):
await search_field.press("Control+a")
await page.wait_for_timeout(50)
await search_field.press("Backspace")
await page.wait_for_timeout(random.uniform(100, 300))
for char in query:
await search_field.press(char)
await page.wait_for_timeout(random.uniform(80, 180))
await page.wait_for_timeout(random.uniform(400, 800))
await page.keyboard.press("Enter")
await page.wait_for_load_state("domcontentloaded", timeout=30000)
await browser_manager.random_delay(3, 6)
if await browser_manager.detect_captcha(page):
await browser_manager.handle_captcha()
try:
await page.wait_for_selector("div[role='feed']", state="visible", timeout=15000)
except Exception:
pass
await page.wait_for_timeout(random.uniform(1000, 2000))
await browser_manager.scroll_sidebar(page, "div[role='feed']", scrolls=14, pause_ms=650)
await page.wait_for_timeout(2000)
await browser_manager.scroll_sidebar(page, "div[role='feed']", scrolls=8, pause_ms=500)
await page.wait_for_timeout(1500)
# Zähle Karten via JS (nie stale)
total_cards = await page.evaluate(
"""() => {
const cards = document.querySelectorAll('a.hfpxzc, a.qBF1Pd, div[role="feed"] a[href*="/maps/place/"]');
return cards.length;
}"""
)
if not total_cards:
total_cards = await page.evaluate(
"""() => document.querySelectorAll('div[role="feed"] > div').length"""
)
logger.info("[Maps] %d Ergebnis-Karten gefunden", total_cards)
for idx in range(min(total_cards, max_results * 2)):
if len(results) >= max_results:
break
# ===== VARIABLEN-RESET =====
name = ""
website = ""
phone = ""
rating = 0
address = ""
email = ""
try:
# Klicke per JS-Index (nie stale)
clicked = await page.evaluate(
"""(idx) => {
const sels = ['a.hfpxzc', 'a.qBF1Pd', 'div[role="feed"] a[href*="/maps/place/"]'];
for (const sel of sels) {
const cards = document.querySelectorAll(sel);
if (cards[idx]) {
cards[idx].scrollIntoView({behavior: 'instant', block: 'center'});
cards[idx].click();
return true;
}
}
return false;
}""",
idx,
)
if not clicked:
continue
await page.wait_for_timeout(random.uniform(2000, 3500))
if await browser_manager.detect_captcha(page):
await browser_manager.handle_captcha()
# Detail-Panel warten
detail_loaded = False
for detail_sel in ["[data-item-id='authority']", "div[role='main']", "section", "h1[data-item-id]", "h1"]:
try:
await page.wait_for_selector(detail_sel, timeout=4000)
detail_loaded = True
break
except Exception:
continue
if not detail_loaded:
continue
# Name
name_el = await page.query_selector("h1[data-item-id]")
if not name_el:
name_el = await page.query_selector("h1.timmcc")
if not name_el:
name_el = await page.query_selector("div.fontHeadlineLarge")
if not name_el:
name_el = await page.query_selector("h1")
if not name_el:
continue
name = (await name_el.inner_text()).strip()
if not name or len(name) < 2 or name in seen_names:
continue
seen_names.add(name)
# Website: aria-label="Website" oder [data-item-id="authority"]
website = await _extract_maps_website(page)
phone = await _extract_maps_phone(page)
rating = await _extract_maps_rating(page)
address = await _extract_maps_address(page)
# Email von Website
if website:
email = await extract_email_from_website(website)
await browser_manager.random_delay(2, 3)
results.append({
"name": name,
"phone": phone,
"website": website,
"email": email,
"source": "google_maps",
"rating": rating,
"address": address,
})
logger.info(
" [Maps] [%d/%d] %s | Web: %s | Email: %s | Tel: %s",
len(results), max_results, name,
website or "—", email or "—", phone or "—",
)
# Panel schließen
try:
await page.keyboard.press("Escape")
await page.wait_for_timeout(600)
except Exception:
pass
await page.mouse.move(random.randint(100, 300), random.randint(100, 300))
await page.wait_for_timeout(random.uniform(800, 1500))
except Exception as e:
logger.debug("[Maps] Eintrag #%d Fehler: %s", idx, e)
try:
await page.keyboard.press("Escape")
await page.wait_for_timeout(500)
except Exception:
pass
continue
if len(results) == 0:
logger.warning("[Maps] 0 Ergebnisse")
else:
logger.info("[Maps] %d Ergebnisse", len(results))
break
except Exception as e:
logger.error("[Maps] Fehlgeschlagen (Versuch %d): %s", attempt, e)
if attempt == 1:
await page.wait_for_timeout(5000)
else:
try:
await page.screenshot(path=str(SCREENSHOTS_DIR / "maps_error.png"), full_page=True)
except Exception:
pass
return results
async def _extract_maps_website(page: Page) -> str:
"""
Extrahiert Website aus Maps Detail-Panel.
1. aria-label*="website"
2. [data-item-id="authority"]
3. Text-Match
"""
def _clean(href: str) -> str:
if not href:
return ""
if "/url?q=" in href:
href = href.split("/url?q=")[1].split("&")[0]
decoded = unquote(href)
if "google" not in decoded.lower() and "maps" not in decoded.lower():
return decoded.split("?")[0]
return ""
try:
# 1. aria-label*="website"
for sel in ['a[aria-label*="website" i]', 'a[aria-label*="Webseite" i]', 'a[aria-label*="Website" i]']:
el = await page.query_selector(sel)
if el:
href = await el.get_attribute("href")
cleaned = _clean(href)
if cleaned:
logger.debug("[Maps] Website via aria-label: %s", cleaned)
return cleaned
# 2. [data-item-id="authority"]
for sel in ['[data-item-id="authority"]', 'a[data-item-id="authority"]', 'button[data-item-id="authority"]']:
el = await page.query_selector(sel)
if el:
href = await el.get_attribute("href")
cleaned = _clean(href)
if cleaned:
logger.debug("[Maps] Website via authority: %s", cleaned)
return cleaned
# 3. data-item-id*="website"
el = await page.query_selector("a[data-item-id*='website']")
if el:
cleaned = _clean(await el.get_attribute("href"))
if cleaned:
return cleaned
# 4. Text-basiert
all_links = await page.query_selector_all("div[role='main'] a[href], section a[href], a[href^='http']")
for link in all_links:
try:
href = await link.get_attribute("href")
text = (await link.inner_text()).strip().lower()
if any(kw in text for kw in ["website", "webseite", "besuchen", "homepage", "zur webseite"]):
cleaned = _clean(href)
if cleaned:
return cleaned
except Exception:
continue
# 5. Erster externer Link
for link in all_links:
try:
href = await link.get_attribute("href")
cleaned = _clean(href)
if cleaned and cleaned.startswith(("http://", "https://")):
return cleaned
except Exception:
continue
except Exception:
pass
return ""
async def _extract_maps_phone(page: Page) -> str:
try:
for sel in ["a[href^='tel:']", "button[data-item-id*='phone']", "div[data-item-id*='phone'] span"]:
el = await page.query_selector(sel)
if el:
if sel.startswith("a[href^='tel:']"):
href = await el.get_attribute("href")
return href.replace("tel:", "").strip() if href else ""
return (await el.inner_text()).strip()
except Exception:
pass
return ""
async def _extract_maps_rating(page: Page) -> float:
try:
for sel in [
"span.fontBodyMedium[aria-label*='Sterne']",
"div[data-item-id*='rating'] span[aria-label]",
"span[aria-label*='rated']",
]:
el = await page.query_selector(sel)
if el:
aria = await el.get_attribute("aria-label") or ""
m = re.search(r"(\d[\.,]?\d?)", aria)
if m:
return float(m.group(1).replace(",", "."))
text = await el.inner_text()
m = re.search(r"(\d[\.,]?\d?)", text)
if m:
return float(m.group(1).replace(",", "."))
except Exception:
pass
return 0
async def _extract_maps_address(page: Page) -> str:
try:
for sel in ["button[data-item-id*='address']", "div[data-item-id*='address']"]:
el = await page.query_selector(sel)
if el:
spans = await el.query_selector_all("span")
if spans:
texts = [await s.inner_text() for s in spans]
return " ".join(t.strip() for t in texts if t.strip())
return (await el.inner_text()).strip()
except Exception:
pass
return ""
# ==============================================================================
# Gelbe Seiten — mit Base64-Fix & Paginierung
# ==============================================================================
async def scrape_gelbe_seiten(
branch: str, city: str, max_results: int = 20,
page: Page = None, radius_km: int = None,
) -> list[dict]:
if not browser_manager or not browser_manager.context:
return []
if page is None:
page = await browser_manager.new_tab()
if radius_km is None:
radius_km = SEARCH_RADIUS_KM
branch_encoded = branch.replace(" ", "-")
city_encoded = city.replace(" ", "-")
umkreis = radius_km * 1000 # in Metern
results = []
seen_names = set()
social_media_domains = [
"facebook.com", "instagram.com", "twitter.com", "x.com",
"linkedin.com", "youtube.com", "tiktok.com", "pinterest.de",
"wa.me", "whatsapp.com",
]
for page_num in range(1, 6):
if len(results) >= max_results:
break
if page_num == 1:
url = f"https://www.gelbeseiten.de/suche/{branch_encoded}/{city_encoded}?umkreis={umkreis}"
else:
url = f"https://www.gelbeseiten.de/suche/{branch_encoded}/{city_encoded}?umkreis={umkreis}&page={page_num}"
logger.info("[GelbeSeiten] Seite %d: %s", page_num, url)
for attempt in range(1, 3):
try:
await browser_manager.random_delay(2, 4)
await page.goto(url, wait_until="domcontentloaded", timeout=30000)
if await browser_manager.detect_captcha(page):
await browser_manager.handle_captcha()
await page.wait_for_timeout(2500)
html = await page.content()
soup = BeautifulSoup(html, "lxml")
entries = soup.select(".modulTeaser, [class*='teaser'], [class*='entry'], article, .result-item")
if not entries:
logger.info("[GelbeSeiten] Seite %d: keine Einträge", page_num)
break
for entry in entries:
if len(results) >= max_results:
break
try:
name_el = entry.select_one("h2, h3, .name, [class*='name'], .business-name")
if not name_el:
continue
name = name_el.get_text(strip=True)
if len(name) < 2 or name in seen_names:
continue
seen_names.add(name)
phone_el = entry.select_one("[class*='phone'], .tel, a[href^='tel:']")
phone = phone_el.get_text(strip=True) if phone_el else ""
website = ""
# ===== BASE64-FIX =====
# data-webseitelink Attribut in <span> Tags
webseite_span = entry.select_one('span[data-webseitelink]')
if webseite_span:
b64_val = webseite_span.get("data-webseitelink", "")
if b64_val:
try:
decoded = base64.b64decode(b64_val).decode('utf-8')
if decoded.startswith("http") and not any(social in decoded.lower() for social in social_media_domains):
website = decoded
logger.debug("[GelbeSeiten] Base64-Link dekodiert: %s", website)
except Exception as e:
logger.debug("[GelbeSeiten] Base64-Dekodierung fehlgeschlagen: %s", e)
# Fallback: data-zve-ad-click-element="website"
if not website:
zve = entry.select_one('a[data-zve-ad-click-element="website"]')
if zve:
href = zve.get("href", "")
if href.startswith("http"):
website = href
# Fallback: Text-Match
if not website:
for link in entry.select("a"):
text = link.get_text(strip=True).lower()
href = link.get("href", "")
if any(kw in text for kw in ["webseite", "website", "zur webseite", "homepage"]):
if href.startswith("http") and not any(social in href.lower() for social in social_media_domains):
if "gelbeseiten.de" not in href.lower():
website = href
break
# Fallback: generische Links
if not website:
for link in entry.select("a[href*='http']"):
href = link.get("href", "")
if not href.startswith("http"):
continue
if any(social in href.lower() for social in social_media_domains):
continue
if "gelbeseiten.de" in href.lower():
continue
website = href
break
address_el = entry.select_one("[class*='address'], [class*='street'], .address")
address = address_el.get_text(strip=True) if address_el else ""
# Email extrahieren
email = ""
if website:
email = await extract_email_from_website(website)
await browser_manager.random_delay(2, 3)
results.append({
"name": name,
"phone": phone,
"website": website,
"email": email,
"source": "gelbe_seiten",
"rating": 0,
"address": address,
})
logger.info(
" [GelbeSeiten] [%d/%d] %s | Web: %s | Email: %s",
len(results), max_results, name,
website or "—", email or "—",
)
except Exception:
continue
logger.info("[GelbeSeiten] Seite %d: %d Einträge, gesamt %d", page_num, len(entries), len(results))
break
except Exception as e:
logger.error("[GelbeSeiten] Seite %d Fehlgeschlagen (Versuch %d): %s", page_num, attempt, e)
if attempt == 1:
await page.wait_for_timeout(5000)
else:
break
# Prüfe nächste Seite
has_next = False
try:
next_btn = await page.query_selector(
'.gs_seitenweiter_link, a.paging__next, [class*="next"], [class*="weiter"], a[title*="Nächste"]'
)
if next_btn and await next_btn.is_visible():
has_next = True
except Exception:
pass
if not has_next and page_num < 5:
logger.info("[GelbeSeiten] Keine weitere Seite")
break
if len(results) == 0:
logger.warning("[GelbeSeiten] 0 Ergebnisse")
else:
logger.info("[GelbeSeiten] %d Ergebnisse gesamt", len(results))
return results
# ==============================================================================
# Das Örtliche — mit Paginierung
# ==============================================================================
async def scrape_das_oertliche(
branch: str, city: str, max_results: int = 20,
page: Page = None, radius_km: int = None,
) -> list[dict]:
if not browser_manager or not browser_manager.context:
return []
if page is None:
page = await browser_manager.new_tab()
if radius_km is None:
radius_km = SEARCH_RADIUS_KM
branch_encoded = branch.replace(" ", "+")
city_encoded = city.replace(" ", "+")
results = []
seen_names = set()
social_media_domains = [
"facebook.com", "instagram.com", "twitter.com", "x.com",
"linkedin.com", "youtube.com", "tiktok.com", "pinterest.de",
"wa.me", "whatsapp.com",
]
for page_num in range(1, 6):
if len(results) >= max_results:
break
if page_num == 1:
url = f"https://www.dasoertliche.de/?form_name=search_nat&zvo_ok=0&worte={branch_encoded}&ort={city_encoded}"
else:
url = f"https://www.dasoertliche.de/?form_name=search_nat&zvo_ok=0&worte={branch_encoded}&ort={city_encoded}&page={page_num}"
logger.info("[DasOertliche] Seite %d", page_num)
for attempt in range(1, 3):
try:
await browser_manager.random_delay(2, 4)
await page.goto(url, wait_until="domcontentloaded", timeout=30000)
if await browser_manager.detect_captcha(page):
await browser_manager.handle_captcha()
await page.wait_for_timeout(2000)
html = await page.content()
soup = BeautifulSoup(html, "lxml")
entries = soup.select(".result, .mod, [class*='result'], [class*='entry'], article, .hit")
if not entries:
break
for entry in entries:
if len(results) >= max_results:
break
try:
name_el = entry.select_one("h2, h3, .name, [class*='name'], .business-name")
if not name_el:
continue
name = name_el.get_text(strip=True)
if len(name) < 2 or name in seen_names:
continue
seen_names.add(name)
phone_el = entry.select_one("[class*='phone'], .tel, a[href^='tel:']")
phone = phone_el.get_text(strip=True) if phone_el else ""
website = ""
for link in entry.select("a[href*='http']"):
href = link.get("href", "")
if not href.startswith("http"):
continue
if any(social in href.lower() for social in social_media_domains):
continue
if "dasoertliche.de" in href.lower():
continue
website = href