-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
1820 lines (1635 loc) · 92.6 KB
/
Copy pathscraper.py
File metadata and controls
1820 lines (1635 loc) · 92.6 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
import re
import os
import time
import random
import tempfile
import threading
import io
import urllib.request
import urllib.parse
from urllib.parse import urlencode, urlparse, parse_qs, quote
from typing import Optional, List, Dict, Union, Tuple
import concurrent.futures
from bs4 import BeautifulSoup
from PIL import Image
try:
from playwright.sync_api import sync_playwright
HAS_PLAYWRIGHT = True
except ImportError:
HAS_PLAYWRIGHT = False
try:
from curl_cffi import requests as curl_requests
HAS_CURL_CFFI = True
except ImportError:
import requests as curl_requests
HAS_CURL_CFFI = False
EBAY_LOCALES = [
{"code": "US", "name": "United States", "domain": "ebay.com", "region": "North America", "flag": "🇺🇸"},
{"code": "UK", "name": "United Kingdom", "domain": "ebay.co.uk", "region": "Europe", "flag": "🇬🇧"},
{"code": "DE", "name": "Germany", "domain": "ebay.de", "region": "Europe", "flag": "🇩🇪"},
{"code": "CA", "name": "Canada", "domain": "ebay.ca", "region": "North America", "flag": "🇨🇦"},
{"code": "AU", "name": "Australia", "domain": "ebay.com.au", "region": "APAC", "flag": "🇦🇺"},
{"code": "FR", "name": "France", "domain": "ebay.fr", "region": "Europe", "flag": "🇫🇷"},
{"code": "IT", "name": "Italy", "domain": "ebay.it", "region": "Europe", "flag": "🇮🇹"},
{"code": "ES", "name": "Spain", "domain": "ebay.es", "region": "Europe", "flag": "🇪🇸"},
{"code": "NL", "name": "Netherlands", "domain": "ebay.nl", "region": "Europe", "flag": "🇳🇱"},
{"code": "PL", "name": "Poland", "domain": "ebay.pl", "region": "Europe", "flag": "🇵🇱"},
{"code": "CH", "name": "Switzerland", "domain": "ebay.ch", "region": "Europe", "flag": "🇨🇭"},
{"code": "AT", "name": "Austria", "domain": "ebay.at", "region": "Europe", "flag": "🇦🇹"},
{"code": "IE", "name": "Ireland", "domain": "ebay.ie", "region": "Europe", "flag": "🇮🇪"},
]
MAX_PAGES = 15
PAGE_SIZE = 60 # eBay standard items per page
class EbayScraper:
def __init__(self, headless=False):
"""
Scraper for eBay store and seller listings with anti-bot bypass and multi-locale support.
"""
self.headless = headless
self.last_scrape_warning = ""
self.is_bot_challenge = False
self.blocked_store_name = ""
self.blocked_store_url = ""
self.profile_dir = os.path.join(
os.environ.get("LOCALAPPDATA", os.path.expanduser("~")),
"Apollo_eBay_Session"
)
os.makedirs(self.profile_dir, exist_ok=True)
def _find_edge_path(self):
browser_paths = [
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
os.path.expandvars(r"%LOCALAPPDATA%\Microsoft\Edge\Application\msedge.exe"),
os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe"),
os.path.expandvars(r"%PROGRAMFILES%\Microsoft\Edge\Application\msedge.exe"),
os.path.expandvars(r"%PROGRAMFILES(X86)%\Microsoft\Edge\Application\msedge.exe"),
os.path.expandvars(r"%PROGRAMFILES%\Google\Chrome\Application\chrome.exe"),
os.path.expandvars(r"%PROGRAMFILES(X86)%\Google\Chrome\Application\chrome.exe"),
]
return next((p for p in browser_paths if os.path.exists(p)), None)
def _clean_ebay_domain(self, domain_str: str) -> str:
"""Resolve standard eBay domain string (e.g., 'ebay.co.uk') from country name, code, or URL."""
if not domain_str:
return "ebay.com"
d = str(domain_str).strip().lower()
if d in ("all", "auto", "reverse", "sweep") or "all locales" in d or "reverse sweep" in d:
return "ebay.com"
m = re.search(r'(?:https?://)?(?:www\.)?(ebay\.[a-z0-9.]+)', d)
if m:
return m.group(1).rstrip("/")
for loc in EBAY_LOCALES:
if loc["code"].lower() == d or loc["name"].lower() in d or loc["domain"] in d:
return loc["domain"]
clean = d.replace("https://", "").replace("http://", "").replace("www.", "").rstrip("/")
return clean if clean.startswith("ebay.") else "ebay.com"
def probe_seller_active_locale(self, target_handle: str) -> Optional[str]:
"""
Fast probe across major international eBay domains to find where an international seller
is actively listing or has a registered store.
Returns the domain string (e.g. 'ebay.co.uk', 'ebay.de') or None.
"""
if not target_handle or target_handle.lower() in ("global", "marketplace", "all products", "catalog", "full search"):
return None
probe_domains = ["ebay.co.uk", "ebay.de", "ebay.ca", "ebay.com.au", "ebay.fr", "ebay.it", "ebay.es", "ebay.nl", "ebay.pl", "ebay.ch", "ebay.at", "ebay.ie"]
clean_handle = target_handle.strip()
for dom in probe_domains:
try:
test_url = f"https://www.{dom}/sch/i.html?_ssn={urllib.parse.quote(clean_handle)}&_ipg=25"
html = self._fetch_via_requests(test_url)
if html:
cards = self._parse_html(html, fallback_seller=clean_handle, domain=dom)
if cards:
return dom
if f"/str/{clean_handle.lower()}" in html.lower() or f"/usr/{clean_handle.lower()}" in html.lower():
return dom
except Exception:
pass
return None
def search_multi_locale(self, store_url: str, include_term: str,
exclude_terms: list[str] = None,
condition: str = "all",
locales: list[str] = None,
stop_event: threading.Event = None,
pause_event: threading.Event = None,
log_callback = None) -> list[dict]:
"""
Cross-border multi-locale sweep across all specified or major eBay regional domains.
"""
target_domains = locales or ["ebay.com", "ebay.co.uk", "ebay.de", "ebay.ca", "ebay.com.au", "ebay.fr", "ebay.it", "ebay.es", "ebay.nl", "ebay.pl"]
all_items = []
seen_ids = set()
def _log(msg):
if log_callback:
try: log_callback(msg)
except Exception: pass
_log(f"🌍 [eBay Multi-Locale Sweep] Searching across {len(target_domains)} regional domains for '{include_term}'...")
for dom in target_domains:
if stop_event and stop_event.is_set():
break
if pause_event:
pause_event.wait()
clean_dom = self._clean_ebay_domain(dom)
_log(f"🌍 [{clean_dom}] Scanning store/seller on {clean_dom}...")
try:
dom_items = self.search(
store_url,
include_term,
exclude_terms=exclude_terms,
condition=condition,
domain=clean_dom,
reverse_locale_probe=False,
stop_event=stop_event,
pause_event=pause_event,
log_callback=log_callback
)
new_in_dom = 0
for it in dom_items:
iid = it.get("item_id")
dedup_key = iid if iid else it.get("url")
if dedup_key and dedup_key not in seen_ids:
seen_ids.add(dedup_key)
all_items.append(it)
new_in_dom += 1
if new_in_dom > 0:
_log(f" ✓ Found {new_in_dom} listings on {clean_dom}.")
except Exception as e:
_log(f" ⚠ Error scanning {clean_dom}: {e}")
return all_items
def search(self, store_url: str, include_term: str,
exclude_terms: list[str] = None,
condition: str = "all",
domain: str = "",
reverse_locale_probe: bool = False,
stop_event: threading.Event = None,
pause_event: threading.Event = None,
log_callback = None) -> list[dict]:
"""
Search an eBay store/seller for include_term on a specific locale domain or with reverse locale auto-detection.
Supports stop_event and pause_event for real-time user control.
"""
def _log(msg):
if log_callback:
try: log_callback(msg)
except Exception: pass
# Check if full multi-locale sweep requested
if domain and any(k in str(domain).lower() for k in ("all", "reverse", "sweep")):
return self.search_multi_locale(
store_url, include_term,
exclude_terms=exclude_terms,
condition=condition,
stop_event=stop_event,
pause_event=pause_event,
log_callback=log_callback
)
self.is_bot_challenge = False
self.blocked_store_name = ""
self.blocked_store_url = ""
store_info = self.resolve_store_info(store_url)
# Override domain if explicitly passed, otherwise use domain detected from store URL
active_dom = self._clean_ebay_domain(domain or store_info.get("domain", "ebay.com"))
store_info["domain"] = active_dom
exclude_terms = exclude_terms or []
cleaned_excludes = self._sanitize_exclusions(include_term, exclude_terms)
items = []
seen_ids = set()
if HAS_PLAYWRIGHT:
try:
items = self._search_via_playwright(
store_info, include_term, cleaned_excludes, condition, seen_ids,
domain=active_dom,
stop_event=stop_event, pause_event=pause_event
)
if items or (stop_event and stop_event.is_set()) or self.is_bot_challenge:
return items
except Exception:
pass
# Fallback to requests search
page = 1
seller_label = store_info.get("store_name") or store_info.get("seller") or ""
target_slug = store_info.get("seller") or store_info.get("store_name") or ""
candidates = self._generate_seller_candidates(target_slug) if target_slug else [""]
active_info = dict(store_info)
# Try candidate handles on page 1
for cand in candidates:
if stop_event and stop_event.is_set():
break
if pause_event:
pause_event.wait()
cand_info = dict(store_info)
if cand:
if store_info.get("is_store") and not store_info.get("seller"):
cand_info["store_name"] = cand
cand_info["seller"] = ""
else:
cand_info["seller"] = cand
cand_info["store_name"] = cand
url = self._build_url(cand_info, include_term, cleaned_excludes, 1, condition, domain=active_dom)
html = self._fetch_via_requests(url)
if not html:
continue
page_items = self._parse_html(html, fallback_seller=cand or seller_label, domain=active_dom)
if page_items:
active_info = cand_info
seller_label = cand or seller_label
for item in page_items:
item_id = item.get("item_id")
dedup_key = item_id if item_id else item.get("url")
if dedup_key and dedup_key not in seen_ids:
seen_ids.add(dedup_key)
items.append(item)
break
if items:
page = 2
while page <= MAX_PAGES:
if stop_event and stop_event.is_set():
break
if pause_event:
pause_event.wait()
url = self._build_url(active_info, include_term, cleaned_excludes, page, condition, domain=active_dom)
html = self._fetch_via_requests(url)
if not html:
break
page_items = self._parse_html(html, fallback_seller=seller_label, domain=active_dom)
if not page_items:
break
new_found = 0
for item in page_items:
item_id = item.get("item_id")
dedup_key = item_id if item_id else item.get("url")
if dedup_key and dedup_key not in seen_ids:
seen_ids.add(dedup_key)
items.append(item)
new_found += 1
if new_found == 0 or len(page_items) < 10:
break
page += 1
time.sleep(random.uniform(1.0, 2.0))
# Reverse Locale Auto-Detection fallback: If 0 results found on requested locale, probe international locales
if not items and reverse_locale_probe and target_slug and target_slug.lower() not in ("global", "marketplace", "all products", "catalog", "full search"):
_log(f"🔍 [Reverse Locale Probe] Checking international eBay locales for seller '{target_slug}'...")
found_locale_dom = self.probe_seller_active_locale(target_slug)
if found_locale_dom and found_locale_dom != active_dom:
_log(f"🌍 [Reverse Locale Match] Seller '{target_slug}' found active on eBay {found_locale_dom}! Harvesting listings...")
return self.search(
store_url,
include_term,
exclude_terms=exclude_terms,
condition=condition,
domain=found_locale_dom,
reverse_locale_probe=False,
stop_event=stop_event,
pause_event=pause_event,
log_callback=log_callback
)
return items
def _get_user_data_dir(self) -> str:
"""Return dedicated persistent user data directory for Playwright."""
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "browser_session")
os.makedirs(base, exist_ok=True)
return base
def open_interactive_solve_window(self, url: str, window_pos: tuple = (100, 100), window_size: tuple = (1100, 800)):
"""Launch a visible browser window using the persistent profile to let analyst solve CAPTCHA."""
if not HAS_PLAYWRIGHT:
import webbrowser
webbrowser.open(url)
return
user_data_dir = self._get_user_data_dir()
edge_path = self._find_edge_path()
try:
with sync_playwright() as p:
launch_kwargs = {
"headless": False,
"viewport": {"width": window_size[0], "height": window_size[1]},
"args": [
"--disable-blink-features=AutomationControlled",
"--no-first-run",
f"--window-position={window_pos[0]},{window_pos[1]}",
f"--window-size={window_size[0]},{window_size[1]}"
]
}
if edge_path:
launch_kwargs["executable_path"] = edge_path
else:
launch_kwargs["channel"] = "msedge"
context = p.chromium.launch_persistent_context(user_data_dir, **launch_kwargs)
page = context.pages[0] if context.pages else context.new_page()
page.goto(url, wait_until="domcontentloaded", timeout=30000)
# Wait for user to interact / solve challenge (up to 25 seconds or until closed)
for _ in range(25):
if page.is_closed():
break
time.sleep(1)
try:
context.close()
except Exception:
pass
except Exception:
import webbrowser
webbrowser.open(url)
def _search_via_playwright(self, store_info: dict,
include_term: str, excludes: list[str],
condition: str, seen_ids: set,
domain: str = "ebay.com",
stop_event: threading.Event = None,
pause_event: threading.Event = None) -> list[dict]:
"""Search across pages using a single browser session with stop/pause support."""
items = []
seller_label = store_info.get("store_name") or store_info.get("seller") or ""
active_dom = self._clean_ebay_domain(domain or store_info.get("domain", "ebay.com"))
host = f"www.{active_dom}" if not active_dom.startswith("www.") and "cafr." not in active_dom else active_dom
user_data_dir = self._get_user_data_dir()
try:
with sync_playwright() as p:
launch_args = [
"--disable-blink-features=AutomationControlled",
"--disable-features=IsolateOrigins,site-per-process",
"--no-first-run",
"--no-default-browser-check"
]
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
edge_path = self._find_edge_path()
launch_kwargs = {
"headless": self.headless,
"user_agent": ua,
"viewport": {"width": 1440, "height": 900},
"args": launch_args
}
if edge_path:
launch_kwargs["executable_path"] = edge_path
else:
launch_kwargs["channel"] = "msedge"
try:
context = p.chromium.launch_persistent_context(user_data_dir, **launch_kwargs)
except Exception:
try:
launch_kwargs.pop("executable_path", None)
launch_kwargs["channel"] = "msedge"
context = p.chromium.launch_persistent_context(user_data_dir, **launch_kwargs)
except Exception:
launch_kwargs["channel"] = "chrome"
context = p.chromium.launch_persistent_context(user_data_dir, **launch_kwargs)
context.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
window.navigator.chrome = { runtime: {} };
Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']});
""")
page = context.pages[0] if context.pages else context.new_page()
# Warm up session with authentic eBay cookies on active domain
try:
page.goto(f"https://{host}", wait_until="domcontentloaded", timeout=12000)
time.sleep(1.8)
except Exception:
pass
# If item URL was passed, resolve the actual seller username from the listing
if store_info.get("is_item") and store_info.get("item_id"):
item_id = store_info["item_id"]
try:
page.goto(f"https://{host}/itm/{item_id}", wait_until="domcontentloaded", timeout=15000)
time.sleep(0.8)
item_html = page.content()
resolved = ""
# Prioritize Store Link, then JSON sellerName, then /usr/ profile link
m_str = re.search(r"/str/([a-zA-Z0-9_.-]+)", item_html)
if m_str and not any(k in m_str.group(1).lower() for k in ("help", "about", "contact")):
resolved = m_str.group(1).strip()
else:
m_j = re.search(r'"sellerName":\s*"([a-zA-Z0-9_.-]+)"', item_html)
if m_j:
resolved = m_j.group(1).strip()
else:
m_usr = re.search(r"/usr/([a-zA-Z0-9_.-]+)", item_html)
resolved = m_usr.group(1).strip() if m_usr else ""
if resolved:
store_info["seller"] = resolved
store_info["store_name"] = resolved
seller_label = resolved
except Exception:
pass
# If store URL was passed without a resolved seller username, resolve it directly in browser
if store_info.get("is_store") and store_info.get("store_name") and not store_info.get("seller"):
try:
page.goto(f"https://{host}/str/{store_info['store_name']}", wait_until="domcontentloaded", timeout=15000)
time.sleep(0.8)
store_html = page.content()
m_ssn = re.search(r'"_ssn":\s*"([a-zA-Z0-9_.-]+)"', store_html)
m_seller = re.search(r'"(?:sellerId|ownerUsername|username)":\s*"([a-zA-Z0-9_.-]+)"', store_html)
m_usr = re.search(r'/usr/([a-zA-Z0-9_.-]+)', store_html)
resolved = ""
if m_ssn and not any(k in m_ssn.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved = m_ssn.group(1).strip()
elif m_seller and not any(k in m_seller.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved = m_seller.group(1).strip()
elif m_usr and not any(k in m_usr.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved = m_usr.group(1).strip()
if resolved:
store_info["seller"] = resolved
seller_label = resolved
except Exception:
pass
target_slug = store_info.get("seller") or store_info.get("store_name") or ""
candidates = self._generate_seller_candidates(target_slug) if target_slug else [""]
active_info = dict(store_info)
# Try candidate variations on Page 1 until a matching handle is found
for cand in candidates:
if stop_event and stop_event.is_set():
break
if pause_event:
pause_event.wait()
cand_info = dict(store_info)
if cand:
if store_info.get("is_store") and not store_info.get("seller"):
cand_info["store_name"] = cand
cand_info["seller"] = ""
else:
cand_info["seller"] = cand
cand_info["store_name"] = cand
url = self._build_url(cand_info, include_term, excludes, 1, condition, domain=active_dom)
try:
page.goto(url, wait_until="domcontentloaded", timeout=20000)
try:
page.wait_for_selector(".s-card, .s-item, .str-item-card, .srp-results, .srp-save-null-search", timeout=6000)
except Exception:
pass
time.sleep(0.6)
# Trigger lazy-loaded items (eBay virtualized stream)
for _ in range(2):
page.evaluate("window.scrollBy(0, 1200)")
time.sleep(0.2)
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(0.4)
html = page.content()
except Exception:
try: html = page.content()
except Exception: html = ""
if not html:
continue
page_items = self._parse_html(html, fallback_seller=cand or seller_label, domain=active_dom)
if not page_items and html:
h_low = html.lower()
if any(k in h_low for k in ("error page | ebay", "pardon our interruption", "something went wrong on our end")) or ("0." in h_low and "ebay" in h_low and "sorry" in h_low):
time.sleep(1.8)
try:
page.goto(url, wait_until="domcontentloaded", timeout=20000)
try:
page.wait_for_selector(".s-card, .s-item, .str-item-card, .srp-results", timeout=5000)
except Exception: pass
time.sleep(0.4)
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(0.3)
html = page.content()
page_items = self._parse_html(html, fallback_seller=cand or seller_label, domain=active_dom)
except Exception:
pass
if page_items:
active_info = cand_info
seller_label = cand or seller_label
for item in page_items:
item_id = item.get("item_id")
dedup_key = item_id if item_id else item.get("url")
if dedup_key and dedup_key not in seen_ids:
seen_ids.add(dedup_key)
items.append(item)
break
# If items found on Page 1, paginate remaining pages with the confirmed handle
if items:
page_num = 2
max_crawl_limit = MAX_PAGES if target_slug else 2
while page_num <= max_crawl_limit:
if stop_event and stop_event.is_set():
break
if pause_event:
pause_event.wait()
url = self._build_url(active_info, include_term, excludes, page_num, condition, domain=active_dom)
try:
page.goto(url, wait_until="domcontentloaded", timeout=20000)
try:
page.wait_for_selector(".s-card, .s-item, .str-item-card, .srp-results, .srp-save-null-search", timeout=5000)
except Exception:
pass
time.sleep(0.6)
# Trigger lazy-loaded items for paginated pages
for _ in range(2):
page.evaluate("window.scrollBy(0, 1200)")
time.sleep(0.2)
page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(0.4)
html = page.content()
except Exception:
try: html = page.content()
except Exception: html = ""
if not html:
break
page_items = self._parse_html(html, fallback_seller=seller_label, domain=active_dom)
if not page_items:
break
new_found = 0
for item in page_items:
item_id = item.get("item_id")
dedup_key = item_id if item_id else item.get("url")
if dedup_key and dedup_key not in seen_ids:
seen_ids.add(dedup_key)
items.append(item)
new_found += 1
if new_found == 0 or len(page_items) < 10:
break
page_num += 1
time.sleep(random.uniform(0.8, 1.5))
if not items and html:
html_low = html.lower()
if any(t in html_low for t in (
"pardon our interruption",
"security measure",
"please verify you are a human",
"access denied",
"something went wrong on our end",
"error page | ebay",
"sorry, something went wrong",
)) or ("0." in html_low and "ebay" in html_low and "sorry" in html_low):
self.is_bot_challenge = True
self.blocked_store_name = seller_label
self.blocked_store_url = url
self.last_scrape_warning = f"⚠ [IP THROTTLE / BOT CHALLENGE] eBay / Akamai rate-limited '{seller_label}' ('Something went wrong on our end' / Error Page) — zero results returned due to temporary edge rate-limit, not empty store."
elif any(t in html_low for t in ("does not exist", "store not found", "seller not found", "we looked everywhere")):
self.last_scrape_warning = f"ℹ Store/Seller '{seller_label}' returned 0 results or store was not found on eBay ({active_dom})."
else:
self.last_scrape_warning = ""
else:
self.last_scrape_warning = ""
try:
context.close()
except Exception:
pass
finally:
pass
return items
# ── Store / Seller Info Resolver ──────────────────────────────────────────
def resolve_store_info(self, url: str) -> dict:
"""
Extract store_name, seller username, domain, and store flag.
Returns dict: {'store_name': str, 'seller': str, 'is_store': bool, 'domain': str}
"""
info = {
"store_name": "",
"seller": "",
"is_store": False,
"domain": "ebay.com"
}
if not url:
return info
url_str = url.strip().rstrip("/")
m_dom = re.search(r'(?:https?://)?(?:www\.)?(ebay\.[a-z0-9.]+)', url_str, re.IGNORECASE)
if m_dom:
info["domain"] = m_dom.group(1).lower()
if any(g in url_str.lower() for g in ("global", "marketplace", "all products", "catalog", "full search")) or url_str.lower() in (
"https://www.ebay.com", "http://www.ebay.com", "https://ebay.com", "http://ebay.com",
"www.ebay.com", "ebay.com", "https://www.ebay.com/sch", "https://www.ebay.com/sch/i.html"
):
return info
# Check for query parameters first (e.g. pasted eBay search URL)
if "?" in url_str:
parsed = urlparse(url_str)
qs = parse_qs(parsed.query)
if "store_name" in qs:
info["store_name"] = qs["store_name"][0].strip()
info["is_store"] = True
if "_ssn" in qs:
info["seller"] = qs["_ssn"][0].strip()
if info["store_name"] or info["seller"]:
return info
# Check for item URL pattern /itm/
m_itm = re.search(r"/itm/(?:[^/]+/)?(\d+)", url_str)
if m_itm:
item_id = m_itm.group(1)
info["item_id"] = item_id
info["is_item"] = True
info["is_store"] = True
return info
# Check for bare 12-digit eBay Item ID
if url_str.isdigit() and len(url_str) >= 10:
info["item_id"] = url_str
info["is_item"] = True
info["is_store"] = True
return info
# Check for store URL pattern /str/
elif "/str/" in url_str.lower():
part = url_str.lower().split("/str/")[-1]
store_name = part.split("/")[0].split("?")[0].strip()
info["store_name"] = store_name
info["is_store"] = True
# Check for user / seller URL pattern /usr/ or /seller/
elif "/usr/" in url_str.lower() or "/seller/" in url_str.lower():
for pattern in ["/usr/", "/seller/"]:
if pattern in url_str.lower():
part = url_str.lower().split(pattern)[-1]
user_name = part.split("/")[0].split("?")[0].strip()
info["seller"] = user_name
info["is_store"] = False
break
# Check /sch/username/m.html pattern
elif re.search(r"/sch/([^/?&#]+)/m\.html", url_str, re.IGNORECASE):
m = re.search(r"/sch/([^/?&#]+)/m\.html", url_str, re.IGNORECASE)
info["seller"] = m.group(1).strip()
info["is_store"] = False
# Plain text input
elif not url_str.startswith("http://") and not url_str.startswith("https://"):
clean_name = url_str.split("/")[0].split("?")[0].strip()
info["store_name"] = clean_name
info["is_store"] = True
else:
# Check if root domain with no store path
parsed = urlparse(url_str)
path_segs = [p for p in parsed.path.split("/") if p]
if not path_segs:
info["store_name"] = ""
info["seller"] = ""
info["is_store"] = False
else:
last_seg = path_segs[-1].split("?")[0].strip()
info["store_name"] = last_seg
info["is_store"] = True
# Automatic Store-to-Seller Bridge: Resolve underlying legal seller ID if store_name is present
if info.get("store_name") and not info.get("seller"):
s_name = info["store_name"].lower()
if not hasattr(self, "_store_seller_cache"):
self._store_seller_cache = {}
if s_name in self._store_seller_cache:
info["seller"] = self._store_seller_cache[s_name]
else:
try:
host = f"www.{info['domain']}" if not info['domain'].startswith("www.") and "cafr." not in info['domain'] else info['domain']
store_html = self._fetch_via_requests(f"https://{host}/str/{info['store_name']}")
if store_html:
m_ssn = re.search(r'"_ssn":\s*"([a-zA-Z0-9_.-]+)"', store_html)
m_seller = re.search(r'"(?:sellerId|ownerUsername|username)":\s*"([a-zA-Z0-9_.-]+)"', store_html)
m_usr = re.search(r'/usr/([a-zA-Z0-9_.-]+)', store_html)
resolved_user = ""
if m_ssn and not any(k in m_ssn.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved_user = m_ssn.group(1).strip()
elif m_seller and not any(k in m_seller.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved_user = m_seller.group(1).strip()
elif m_usr and not any(k in m_usr.group(1).lower() for k in ("help", "about", "contact", "signin", "register")):
resolved_user = m_usr.group(1).strip()
if resolved_user:
self._store_seller_cache[s_name] = resolved_user
info["seller"] = resolved_user
except Exception:
pass
return info
def _generate_seller_candidates(self, slug: str) -> list[str]:
"""Return the exact target handle without mangling underscores or hyphens."""
if not slug:
return [""]
clean = slug.strip()
return [clean]
def resolve_seller(self, url: str) -> str:
"""Backwards compatibility for main.py."""
if not url or any(g in url.lower() for g in ("global", "marketplace", "all products", "catalog", "full search")):
return "eBay Global Search"
info = self.resolve_store_info(url)
return info.get("store_name") or info.get("seller") or "eBay Global Search"
# ── Exclusion Sanitizer ───────────────────────────────────────────────────
def _sanitize_exclusions(self, include_term: str, exclude_terms: list[str]) -> list[str]:
"""
Ensure no exclusion term contradicts or cancels out the search term.
"""
inc_lower = include_term.lower()
inc_tokens = set(re.findall(r"\w+", inc_lower))
safe_excludes = []
for ex in exclude_terms:
ex_clean = ex.strip().strip('"')
if not ex_clean:
continue
ex_lower = ex_clean.lower()
ex_tokens = set(re.findall(r"\w+", ex_lower))
if ex_lower == inc_lower or (ex_tokens and ex_tokens.issubset(inc_tokens)):
continue
safe_excludes.append(ex_clean)
return safe_excludes
# ── URL Builder ───────────────────────────────────────────────────────────
def _build_url(self, store_info: dict, include: str, excludes: list[str],
page: int, condition: str = "all", domain: str = "") -> str:
"""
Build eBay search URL matching native store or seller search on specified or default locale domain.
Handles multi-word exclusions properly by wrapping them in quotes (e.g. -"General Motors").
"""
nkw_parts = []
if include and include.strip():
nkw_parts.append(include.strip())
for ex in excludes:
ex_str = ex.strip().strip('"')
if ex_str:
if " " in ex_str:
nkw_parts.append(f'-"{ex_str}"')
else:
nkw_parts.append(f"-{ex_str}")
nkw = " ".join(nkw_parts).strip()
if isinstance(store_info, str):
store_name = store_info
seller = store_info
target_dom = domain or "ebay.com"
elif isinstance(store_info, dict):
store_name = store_info.get("store_name", "")
seller = store_info.get("seller", "")
target_dom = domain or store_info.get("domain", "ebay.com")
else:
store_name = ""
seller = ""
target_dom = domain or "ebay.com"
clean_dom = self._clean_ebay_domain(target_dom)
host = f"www.{clean_dom}" if not clean_dom.startswith("www.") and "cafr." not in clean_dom else clean_dom
params = {
"_from": "R40",
"_sacat": "0",
"_ipg": PAGE_SIZE
}
target_handle = seller or store_name
if target_handle:
params["_ssn"] = target_handle
if nkw:
params["_nkw"] = nkw
else:
params["_armrs"] = "1"
else:
params["_nkw"] = nkw if nkw else ""
if page > 1:
params["_pgn"] = page
if condition == "new":
params["LH_ItemCondition"] = "1000"
elif condition == "used":
params["LH_ItemCondition"] = "3000"
return f"https://{host}/sch/i.html?" + urlencode(params)
def _fetch_via_requests(self, url: str) -> str:
"""Fallback fetch using session."""
try:
if HAS_CURL_CFFI:
session = curl_requests.Session(impersonate="chrome124")
else:
session = curl_requests.Session()
session.headers.update({
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
),
"Accept-Language": "en-US,en;q=0.9",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
})
resp = session.get(url, timeout=15)
return resp.text if resp.status_code == 200 else ""
except Exception:
return ""
def _parse_html(self, html: str, fallback_seller: str = "", include_term: str = "", domain: str = "ebay.com") -> list[dict]:
"""
Parse listing items from modern .s-card, classic .s-item, and store layouts.
Extracts robust high-resolution thumbnail URLs.
Filters out rewritten/sponsored overflow items (e.g. 'Results matching fewer words').
"""
soup = BeautifulSoup(html, "html.parser")
items = []
all_cards = soup.select(
"li.s-card, li.s-item, div.s-item__wrapper, li.srp-results__item, .str-item-card, div.str-item-card__wrapper"
)
# Locate rewrite or recommendation divider if present on page
rewrite_banner = soup.find(class_=re.compile(r'REWRITE_START|AUTO_CORRECT_START|s-item--section-title|srp-river-answer--REWRITE', re.I))
if not rewrite_banner:
for h in soup.find_all(["h2", "h3", "div", "span"], string=re.compile(r'results matching fewer words|more items related to|items matching your search keywords|explore more options', re.I)):
rewrite_banner = h
break
for card in all_cards:
# If this card comes AFTER an eBay recommendation / rewrite banner: HARD BREAK!
if rewrite_banner and card in rewrite_banner.find_all_next():
break
card_text = card.get_text(" ", strip=True).lower()
if any(k in card_text for k in ("results matching fewer words", "more items related to", "items matching your search keywords", "explore more options")):
break
if card.select_one(".s-item__placeholder") or card.select_one(".srp-river-answer"):
continue
if card.find_parent(class_=re.compile(r'carousel|sponsored|rewritten|recommendation', re.I)):
continue
# Check if item is located inside or after an eBay rewrite divider (e.g. 'Results matching fewer words')
is_rewritten = False
for prev in card.find_all_previous(class_=True, limit=8):
classes = " ".join(prev.get("class", []))
if any(k in classes for k in ("REWRITE_START", "AUTO_CORRECT_START", "SPONSORED_CONTAINER")):
is_rewritten = True
break
if is_rewritten:
break
# 1. URL & Item ID
link_el = (
card.select_one('a[href*="/itm/"]') or
card.select_one("a.s-item__link, a.s-card__link, a.str-item-card__link")
)
if not link_el or not link_el.get("href"):
continue
raw_url = link_el["href"]
if not raw_url.startswith("http"):
clean_dom = self._clean_ebay_domain(domain)
host = f"www.{clean_dom}" if not clean_dom.startswith("www.") and "cafr." not in clean_dom else clean_dom
raw_url = f"https://{host}{raw_url}"
item_url = raw_url.split("?")[0]
item_id = self._extract_item_id(raw_url)
# 2. Title
title_el = (
card.select_one(".s-card__title") or
card.select_one(".s-item__title") or
card.select_one(".str-item-card__title") or
card.select_one('[role="heading"]') or
card.select_one("h3")
)
if title_el:
for sub_el in title_el.select(".s-item__dynamic-subtitle, .s-card__subtitle, .s-item__subtitle, .s-item__title--tag"):
sub_el.decompose()
title = title_el.get_text(strip=True)
else:
title = link_el.get_text(strip=True) if link_el else ""
if not title or title.lower() == "shop on ebay":
continue
if "Opens in a new window or tab" in title:
title = title.replace("Opens in a new window or tab", "").strip()
if title.startswith("New Listing"):
title = title.replace("New Listing", "", 1).strip()
# Clean surgical eBay inline vehicle compatibility tags ONLY at the very end in parentheses
title = re.sub(r'\s*\((?:For|Fits|Compatible with|Fits for):\s*[^)]+\)\s*$', '', title, flags=re.IGNORECASE).strip()
# 3. Price
price_el = (
card.select_one(".s-card__price") or
card.select_one(".s-item__price") or
card.select_one(".str-item-card__price") or
card.select_one(".s-item__detail--primary .s-item__price") or
card.select_one("[class*='price']")
)
price = ""
if price_el:
# Remove child discount / shipping / logistics spans to prevent badge contamination
for bad_span in price_el.select(".s-item__discount, .s-item__logisticsCost, .s-item__purchase-options, .clipped, .s-item__dynamic, [class*='discount'], [class*='shipping']"):
bad_span.decompose()
raw_price = price_el.get_text(strip=True)
# Regex search for genuine currency or explicit decimal price pattern (e.g. $19.99, US $24.50, 19.99)
m_price = re.search(r'(?:[\$\£\€\¥\₹]|(?:US|USD|EUR|GBP|AUD|CAD|MXN|BRL)\s*\$?)\s*[\d,]+(?:\.\d{2})?|\b[\d,]+\.\d{2}\b', raw_price, flags=re.IGNORECASE)
if m_price and not any(w in raw_price.lower() for w in ("free", "off", "delivery", "shipping", "%", "save")):
price = m_price.group(0).strip()
elif raw_price and any(c in raw_price for c in ("$", "£", "€", "¥")) and not any(w in raw_price.lower() for w in ("free", "delivery", "shipping", "%")):
price = raw_price
from exporter import normalize_price_string
price = normalize_price_string(price)
# 4. Thumbnail Image URL & Authoritative Title Extraction
img_url = ""
img_el = (
card.select_one('img[src*="ebayimg.com"]') or
card.select_one('img[data-src*="ebayimg.com"]') or
card.select_one('img[data-defer-src*="ebayimg.com"]') or
card.select_one('img[data-lazy-src*="ebayimg.com"]') or
card.select_one("img.s-card__image") or
card.select_one("img.s-item__image-img") or
card.select_one(".str-item-card__image img") or
card.select_one("img")
)
if img_el:
# If img_el has a clean, original seller title in alt, prefer it over eBay's modified card span
alt_txt = (img_el.get("alt") or "").strip()
if len(alt_txt) >= 8 and not alt_txt.lower().startswith(("opens in", "item", "product", "image", "thumbnail")):
if title.startswith(alt_txt) or "(for:" in title.lower() or "(fits:" in title.lower():
title = alt_txt
candidates = [