-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselenium_scraper.py
More file actions
1771 lines (1532 loc) · 76.3 KB
/
selenium_scraper.py
File metadata and controls
1771 lines (1532 loc) · 76.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
import random
import subprocess
import time
import shutil
import signal
import abc
import os
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from bs4.element import Comment
from ural import is_url
from requests.utils import requote_uri
from urllib.parse import urlparse, parse_qs, unquote
from backend.lib.search import Search
from common.lib.exceptions import ProcessorException
from common.lib.user_input import UserInput
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import WebDriverException, SessionNotCreatedException, UnexpectedAlertPresentException, \
TimeoutException, JavascriptException, NoAlertPresentException, ElementClickInterceptedException, InvalidSessionIdException, \
ElementNotInteractableException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
########################################################
# This is to attempt to fix a bug in Selenium's logger #
########################################################
import logging
class CustomFormatter(logging.Formatter):
def format(self, record):
if not hasattr(record, 'location'):
record.location = 'N/A'
return super().format(record)
class SeleniumWrapper(metaclass=abc.ABCMeta):
"""
Selenium Scraper class
Selenium utilizes a chrome webdriver and chrome browser to navigate and scrape the web. This processor can be used
to initialize that browser and navigate it as needed. It replaces search to allow you to utilize the Selenium driver
and ensure the webdriver and browser are properly closed out upon completion.
"""
driver = None
last_scraped_url = None
browser = None
eager_selenium = False
selenium_log = None
config = None
_setup_done = False
browser_pid = None
consecutive_errors = 0
num_consecutive_errors_before_restart = 3
_temp_profile_path = None
_temp_profile_is_temp = False
def setup(self, config):
"""
Setup the SeleniumWrapper. This injects the config object and sets up the logger.
"""
self.config = config
# Setup the logger
# I would prefer to use our log class but it seems to cause issue with selenium's logger
formatter = CustomFormatter('%(asctime)s - %(name)s - %(levelname)s - %(location)s - %(message)s')
self.selenium_log = logging.getLogger('selenium')
self.selenium_log.setLevel(logging.INFO)
# ensure we only add a file handler once (avoid duplicate log entries)
log_path = str(self.config.get("PATH_LOGS").joinpath('selenium.log'))
existing = False
for h in list(self.selenium_log.handlers):
try:
if isinstance(h, logging.FileHandler) and os.path.abspath(getattr(h, 'baseFilename', '')) == os.path.abspath(log_path):
# update formatter in case it's changed and mark as present
h.setFormatter(formatter)
existing = True
break
except Exception:
continue
if not existing:
file_handler = logging.FileHandler(log_path)
file_handler.setFormatter(formatter)
self.selenium_log.addHandler(file_handler)
# Avoid propagating to ancestor loggers (prevents duplicate writes if root logger also has handlers)
self.selenium_log.propagate = False
self._setup_done = True
def get_firefox_neterror_info(self):
"""
Returns (is_neterror, reason, target_url, raw_url) based on Firefox about:neterror.
"""
try:
current = self.driver.current_url
except UnexpectedAlertPresentException:
self.dismiss_alert()
current = self.driver.current_url
if isinstance(current, str) and current.startswith("about:neterror"):
try:
qs = parse_qs(urlparse(current).query)
reason = (qs.get("e", [""])[0] or "").strip()
target = unquote((qs.get("u", [""])[0] or "").strip())
return True, reason, target, current
except Exception:
return True, "", "", current
return False, "", "", current
@staticmethod
def add_cookies(driver, cookies, url=None):
"""
Add a cookie or list of cookies to a Selenium `driver`.
Tries three strategies per cookie to maximise compatibility across driver versions:
1. Full fidelity — cookie dict as-is (expiry coerced to int).
2. W3C pruned — drop keys not in the W3C WebDriver spec (handles drivers that
reject unknown fields); sameSite is included here since modern
geckodriver supports it.
3. Minimal safe — name/value/domain/path/secure/httpOnly/expiry only (broadest
compatibility with older drivers).
cookies: dict or list of dicts. Each cookie must include 'name' and 'value'.
Optional keys: 'domain', 'path', 'expiry' (unix seconds), 'secure',
'httpOnly', 'sameSite'.
url: optional full URL (scheme+host) to navigate to first — required if cookie
domain must match current page origin.
Returns a list of (cookie_name, exception) tuples for cookies that could not be
added under any strategy.
"""
if not isinstance(cookies, (list, tuple)):
cookies = [cookies]
if url:
driver.get(url)
# Keys accepted by modern W3C WebDriver (geckodriver ≥ 0.30, chromedriver ≥ 100)
_w3c_keys = {'name', 'value', 'path', 'domain', 'secure', 'httpOnly', 'expiry', 'sameSite'}
# Minimal set for older/stricter driver versions
_minimal_keys = {'name', 'value', 'path', 'domain', 'secure', 'httpOnly', 'expiry'}
failures = []
for c in cookies:
cookie = c.copy()
# Coerce expiry to int; remove it if not convertible
if 'expiry' in cookie and cookie['expiry'] is not None:
try:
cookie['expiry'] = int(cookie['expiry'])
except (TypeError, ValueError):
del cookie['expiry']
name = cookie.get('name', '<unknown>')
# Strategy 1: full cookie dict as-is
try:
driver.add_cookie(cookie)
continue
except Exception:
pass
# Strategy 2: W3C keys (drops any custom/unknown fields the driver rejects)
try:
pruned_w3c = {k: v for k, v in cookie.items() if k in _w3c_keys and v is not None}
driver.add_cookie(pruned_w3c)
continue
except Exception:
pass
# Strategy 3: minimal safe set
try:
pruned_min = {k: v for k, v in cookie.items() if k in _minimal_keys and v is not None}
driver.add_cookie(pruned_min)
continue
except Exception as e_min:
failures.append((name, e_min))
return failures
def _normalize_domain(self, domain: str):
"""Normalize a cookie domain (strip leading dot and lower-case)."""
if not domain:
return None
return domain.lstrip('.').lower()
def _domain_matches(self, host: str, cookie_domain: str):
"""Return True if `cookie_domain` applies to `host` (handles subdomains)."""
if not host or not cookie_domain:
return False
host = host.lower()
cd = self._normalize_domain(cookie_domain)
if host == cd:
return True
# match subdomains
return host.endswith('.' + cd)
def _group_cookies_by_domain(self, cookie_jar, default_host=None):
"""Group a list of cookie dicts by normalized domain.
Cookies without a `domain` key are assigned to `default_host`.
Returns a dict: {normalized_domain: [cookie_dict, ...]}
"""
grouped = {}
if not cookie_jar:
return grouped
for c in cookie_jar:
domain = c.get('domain')
if domain:
nd = self._normalize_domain(domain)
else:
nd = default_host.lower() if default_host else None
if not nd:
continue
grouped.setdefault(nd, []).append(c)
return grouped
def apply_cookies_for_url(self, url, cookie_jar):
"""Apply cookies appropriate for `url` from `cookie_jar`.
Returns a list of errors encountered (empty if none).
"""
errors = []
if not cookie_jar:
return [Exception("No cookies provided in cookie_jar")]
if not self.driver:
return [Exception("Selenium driver not initialized")]
try:
host = urlparse(url).hostname
except Exception:
host = None
if not host:
return [Exception("Invalid URL or unable to extract hostname")]
grouped = self._group_cookies_by_domain(cookie_jar, default_host=host)
# Ensure cache exists
if not hasattr(self, '_cookie_domains_applied') or self._cookie_domains_applied is None:
self._cookie_domains_applied = set()
for domain, cookies in grouped.items():
# Only apply cookies that match the target host
if not self._domain_matches(host, domain) and domain != host:
continue
if domain in self._cookie_domains_applied:
# already applied for this session
continue
# choose scheme: prefer https if any cookie is secure
scheme = 'https' if any(c.get('secure') for c in cookies) else 'http'
origin = f"{scheme}://{domain}"
# Navigate to domain once to set context for cookies; required for Selenium to accept them
self.driver.get(origin)
try:
# Add cookies; add_cookies() returns (name, exc) pairs for any that failed
add_failures = type(self).add_cookies(self.driver, cookies)
self._cookie_domains_applied.add(domain)
# Log per-cookie failures (all three strategies exhausted)
for cookie_name, exc in (add_failures or []):
msg = f"Failed to add cookie '{cookie_name}' for {domain} (all strategies): {type(exc).__name__}: {repr(exc)}"
if self.selenium_log:
self.selenium_log.warning(msg)
errors.append(exc)
# Verify which cookies landed and log discrepancies to aid debugging
if hasattr(self, 'selenium_log') and self.selenium_log and self.selenium_log.isEnabledFor(logging.DEBUG):
try:
present = {c['name']: c for c in self.driver.get_cookies()}
for ck in cookies:
cname = ck.get('name')
if not cname:
continue
cur = present.get(cname)
if not cur:
self.selenium_log.warning(f"Cookie '{cname}' not present in browser after add (domain={domain})")
else:
diffs = []
for key in ('value', 'domain', 'path', 'secure', 'httpOnly', 'expiry', 'sameSite'):
req_val = ck.get(key)
got_val = cur.get(key)
if req_val is None and got_val is None:
continue
if str(req_val) != str(got_val):
diffs.append((key, req_val, got_val))
if diffs:
self.selenium_log.debug(f"Cookie '{cname}' stored with diffs vs requested: {diffs}")
except Exception as e:
self.selenium_log.warning(f"Error verifying cookies for {domain}: {type(e).__name__}: {repr(e)}")
except Exception as e:
# Catch unexpected errors from the overall block (navigation, etc.)
try:
if hasattr(self, 'selenium_log') and self.selenium_log:
self.selenium_log.warning(f"Error applying cookies for {domain}: {type(e).__name__}: {repr(e)}")
except Exception:
pass
errors.append(e)
return errors
def get_with_error_handling(self, url, max_attempts=1, wait=0, cookie_jar=None, restart_browser=True):
"""
Attempts to call driver.get(url) with error handling. Will attempt to restart Selenium if it fails and can
attempt to kill Firefox (and allow Selenium to restart) itself if allowed.
Returns a tuple containing a bool (True if successful, False if not) and a list of the errors raised.
:param str url: URL to retrieve
:param int max_attempts: Maximum number of attempts to retrieve the URL
:param int wait: Seconds to wait between attempts
:param list cookie_jar: List of cookies to add to the driver
:param bool restart_browser: If True, will kill the browser process if too many consecutive errors occur
"""
# Start clean
try:
self.reset_current_page()
except InvalidSessionIdException:
# Somehow we lost the session; restart Selenium
self.restart_selenium()
success = False
attempts = 0
errors = []
# Apply any user-provided cookies appropriate for this URL
if cookie_jar:
try:
cookie_errors = self.apply_cookies_for_url(url, cookie_jar)
if cookie_errors:
# convert exceptions/messages into errors list for caller visibility
[errors.append(e) for e in cookie_errors]
except Exception as e:
errors.append(e)
while attempts < max_attempts:
attempts += 1
try:
# Wrap navigation to auto-handle sporadic, unexpected alerts without JS overrides
self.safe_action(lambda: self.driver.get(url))
# Detect Firefox neterror and treat as failure
is_ne, reason, target, raw = self.get_firefox_neterror_info()
if is_ne:
msg = f"Firefox neterror '{reason or 'unknown'}' loading {target or url}"
self.selenium_log.warning(msg)
errors.append(msg)
success = False
self.consecutive_errors += 1
else:
success = True
self.consecutive_errors = 0
except TimeoutException as e:
errors.append(f"Timeout retrieving {url}: {e}")
except Exception as e:
self.selenium_log.error(f"Error driver.get({url}){(' (dataset '+self.dataset.key+') ') if hasattr(self, 'dataset') else ''}: {e}")
errors.append(e)
self.consecutive_errors += 1
# Restart after too many consecutive failures
if self.consecutive_errors > self.num_consecutive_errors_before_restart:
self.restart_selenium(kill_browser=restart_browser)
if success:
# Check for movement
if self.check_for_movement():
# True success
break
else:
success = False
errors.append(f"Failed to navigate to new page (current URL: {self.last_scraped_url}); check url is not the same as previous url")
if attempts < max_attempts:
time.sleep(wait)
# self.selenium_log.debug(f"Current cookies: {self.driver.get_cookies() if self.driver else 'N/A'}")
return success, errors
def simple_scrape_page(self, url, extract_links=False, title_404_strings='default', wait=0, max_attempts=1, user_cookies=None):
"""
Simple helper to scrape url. Returns a dictionary containing basic results from scrape including final_url,
page_title, and page_source otherwise False if the page did not advance (self.check_for_movement() failed).
Does not handle errors from driver.get() (e.g., badly formed URLs, Timeouts, etc.).
Note: calls self.reset_current_page() prior to requesting url to ensure each page is uniquely checked.
You are invited to use this as a template for more complex scraping.
:param str url: url as string; beginning with scheme (e.g., http, https)
:param List title_404_strings: List of strings representing possible 404 text to be compared with driver.title
:return dict: A dictionary containing basic results from scrape including final_url, page_title, and page_source.
Returns false if no movement was detected
"""
get_success, errors = self.get_with_error_handling(url, cookie_jar=user_cookies, max_attempts=max_attempts, wait=wait, restart_browser=True)
if get_success:
result = self.collect_results(url, extract_links, title_404_strings)
if errors:
result['errors'].extend(errors)
return result
else:
if errors:
return {'errors': errors}
return False
def collect_results(self, url, extract_links=False, title_404_strings='default'):
"""
Collect results from the current page. Returns a dictionary containing basic results from scrape including final_url,
page_title, and page_source. Optionally can include links if extract_links is True. Handles errors from driver.title, driver.current_url, and driver.page_source gracefully by logging the error and including it in the returned dictionary under an 'errors' key as a list of error messages. Note that if an error occurs when trying to access any of these properties, the corresponding value in the returned dictionary will be an empty string.
:param str url: url as string; beginning with scheme (e.g., http, https)
:param bool extract_links: Whether to extract links from the page
:param List title_404_strings: List of strings representing possible 404 text to be compared with driver.title
:return dict: A dictionary containing basic results from scrape including final_url, page_title, and page_source.
"""
errors = []
try:
detected_404 = self.check_for_404(title_404_strings)
except Exception as e:
self.selenium_log.warning(f"Error checking for 404: {e}")
errors.append(e)
detected_404 = False
try:
title = self.driver.title
except Exception as e:
self.selenium_log.warning(f"Error getting page title: {e}")
errors.append(e)
title = ""
try:
final_url = self.driver.current_url
except Exception as e:
self.selenium_log.warning(f"Error getting final URL: {e}")
errors.append(e)
final_url = ""
try:
page_source = self.driver.page_source
except Exception as e:
self.selenium_log.warning(f"Error getting page source: {e}")
errors.append(e)
page_source = ""
result = {
'original_url': url,
'detected_404': detected_404,
'page_title': title,
'final_url': final_url,
'page_source': page_source,
'errors': errors
}
if extract_links:
try:
result['links'] = self.collect_links()
except Exception as e:
self.selenium_log.warning(f"Error collecting links: {e}")
result['errors'].append(e)
result["success"] = True if final_url and page_source and not detected_404 else False
return result
def collect_links(self):
"""
Collect all links on the current page. Returns a list of URLs (strings).
"""
if self.driver is None:
raise ProcessorException('Selenium Drive not yet started: Cannot collect links')
elems = self.driver.find_elements(By.XPATH, "//a[@href]")
return [elem.get_attribute("href") for elem in elems]
@staticmethod
def check_exclude_link(link, previously_used_links, base_url=None, bad_url_list=None):
"""
Check if a link should not be used. Returns True if link not in previously_used_links
and not in bad_url_list. If a base_url is included, the link string MUST include the
base_url as a substring (this can be used to ensure a url contains a particular domain).
If bad_url_lists is None, the default list (['mailto:', 'javascript']) is used.
:param str link: link to check
:param set previously_used_links: set of links to exclude
:param str base_url: substring to ensure is part of link
:param list bad_url_list: list of substrings to exclude
:return bool: True if link should NOT be excluded else False
"""
if bad_url_list is None:
bad_url_list = ['mailto:', 'javascript']
if link and link not in previously_used_links and \
not any([bad_url in link[:len(bad_url)] for bad_url in bad_url_list]):
if base_url is None:
return True
elif base_url in link:
return True
else:
return False
else:
return False
def start_selenium(self, browser=None, eager=None, proxy=None, config=None):
"""
Start a browser with Selenium
:param bool eager: Eager loading? If None, uses class attribute self.eager_selenium (default False)
"""
# Ensure we have a config object
if not self._setup_done:
# config can be passed directly
if config is not None:
self.setup(config)
elif self.config is not None:
# BasicWorkers (e.g., Search) will have a config object set during `process`
self.setup(self.config)
else:
raise ProcessorException("SeleniumWrapper not setup; please call setup() with a config object before starting Selenium.")
self.proxy = proxy
if eager is not None:
# Update eager loading
self.eager_selenium = eager
if browser is not None:
# Update browser type
self.browser = browser
elif self.browser is None:
# Use configured default browser
self.browser = self.config.get('selenium.browser')
# Track which domains we've already applied cookies for in this session
self._cookie_domains_applied = set()
self.selenium_log.info(f"Starting Selenium with browser: {self.browser}")
if self.browser != "firefox":
raise NotImplementedError("Currently only Firefox is supported")
else:
self.setup_firefox()
self.last_scraped_url = None
self.browser_pid = self.driver.service.process.pid
def setup_firefox(self):
"""
Setup Firefox-specific options for Selenium.
"""
driver_start = time.time()
options = FirefoxOptions()
# Configure virtual display vs headless mode
self.setup_virtual_display_mode(options, "firefox")
# Resolve profile first so we can decide whether to start in private mode.
# A user-configured path takes priority; if none is set, create a fresh temp profile
# for this session so each job gets a clean, isolated browser context.
profile_path = None
try:
profile_path = self.get_profile()
if not profile_path:
profile_path = self._create_temp_profile()
except Exception as e:
self.selenium_log.warning(f"Could not resolve Firefox profile: {e}")
# Firefox-specific options
options.add_argument('--no-sandbox')
options.add_argument("--disable-gpu")
options.add_argument("--disable-extensions")
# Base preferences
options.set_preference("dom.webdriver.enabled", False)
options.set_preference('useAutomationExtension', False)
options.set_preference("browser.cache.disk.enable", False)
options.set_preference("browser.cache.memory.enable", False)
if not profile_path:
# No profile available — use private mode for basic session isolation
options.add_argument("--private")
options.set_preference("browser.privatebrowsing.autostart", True)
# Optionally adjust prefs that reduce disruptive dialogs; kept behind config for stealth
if self.config.get('selenium.reduce_dialog_prefs', False):
options.set_preference("dom.webnotifications.enabled", False)
options.set_preference("dom.push.enabled", False)
# Disabling beforeunload prevents sites from prompting on leave; toggle off if detection suspected
options.set_preference("dom.disable_beforeunload", True)
# Configure unhandled prompt behavior (internal to webdriver; page JS cannot read)
try:
behavior = self.config.get('selenium.unhandled_prompt_behavior', 'dismiss') if self.config else 'dismiss'
# W3C capability name
options.set_capability('unhandledPromptBehavior', behavior)
except Exception:
pass
# TODO: setting to block images; REMOVE for screenshot capture
# options.set_preference("permissions.default.image", 2) # Block images for speed
# Eager loading
if self.eager_selenium:
options.set_capability("pageLoadStrategy", "eager")
# Set custom user agent
user_agent = self.get_user_agent()
options.set_preference("general.useragent.override", user_agent)
# Configure proxy if provided
if self.proxy is not None:
# Parse proxy string (expected format: "protocol://host:port" or "host:port")
if "://" in self.proxy:
proxy_parts = self.proxy.split("://")
proxy_type = proxy_parts[0].lower()
proxy_host_port = proxy_parts[1]
else:
proxy_type = "http" # Default to HTTP proxy
proxy_host_port = self.proxy
if ":" in proxy_host_port:
proxy_host, proxy_port = proxy_host_port.split(":")
proxy_port = int(proxy_port)
else:
proxy_host = proxy_host_port
proxy_port = 8080 # Default port
# Set proxy preferences
if proxy_type in ["http", "https"]:
options.set_preference("network.proxy.type", 1) # Manual proxy configuration
options.set_preference("network.proxy.http", proxy_host)
options.set_preference("network.proxy.http_port", proxy_port)
options.set_preference("network.proxy.ssl", proxy_host)
options.set_preference("network.proxy.ssl_port", proxy_port)
elif proxy_type == "socks":
options.set_preference("network.proxy.type", 1)
options.set_preference("network.proxy.socks", proxy_host)
options.set_preference("network.proxy.socks_port", proxy_port)
options.set_preference("network.proxy.socks_version", 5) # SOCKS5
# Don't use proxy for localhost
options.set_preference("network.proxy.no_proxies_on", "localhost, 127.0.0.1")
# Set Firefox binary path if configured
firefox_binary = self.config.get('selenium.firefox_binary_path', None)
if firefox_binary and os.path.exists(firefox_binary):
options.binary_location = firefox_binary
self.selenium_log.info(f"Using custom Firefox binary: {firefox_binary}")
# Apply the resolved profile (user-provided or temp)
if profile_path:
options.add_argument(f'--profile={profile_path}')
self.selenium_log.info(f"Using Firefox profile: {profile_path}")
try:
# Create Firefox service with configurable geckodriver path
service_kwargs = {"log_output": str(self.config.get("PATH_LOGS").joinpath('geckodriver.log'))}
geckodriver_path = self.config.get('selenium.selenium_executable_path', '/usr/local/bin/geckodriver')
if geckodriver_path and os.path.exists(geckodriver_path):
service_kwargs['executable_path'] = geckodriver_path
self.selenium_log.debug(f"Using custom geckodriver: {geckodriver_path}")
self.selenium_log.debug("Selenium env: DISPLAY=%s, LIBGL_ALWAYS_SOFTWARE=%s", os.environ.get('DISPLAY'), os.environ.get('LIBGL_ALWAYS_SOFTWARE'))
self.selenium_log.debug("Will start geckodriver with kwargs: %s", service_kwargs)
service = FirefoxService(**service_kwargs)
# Create Firefox driver
self.driver = webdriver.Firefox(service=service, options=options)
# Apply common configuration
self.apply_common_driver_config()
except (SessionNotCreatedException, WebDriverException) as e:
self.selenium_log.error(f"Error starting Firefox driver: {e}")
raise ProcessorException("Could not connect to browser (%s)." % str(e))
except Exception as e:
self.selenium_log.error(f"Unexpected error starting Firefox driver: {e}")
try:
gl = str(self.config.get("PATH_LOGS").joinpath('geckodriver.log'))
if os.path.exists(gl):
with open(gl,'rb') as f:
f.seek(0,2)
size = f.tell()
f.seek(max(0, size-20000))
tail = f.read().decode('utf-8', errors='replace')
self.selenium_log.error("Geckodriver tail:\n%s", tail)
except Exception:
pass
raise ProcessorException("Unexpected error starting browser: %s" % str(e))
driver_time = time.time() - driver_start
self.selenium_log.info(f"Firefox driver creation took: {driver_time:.2f}s (PID: {self.driver.service.process.pid})")
def setup_virtual_display_mode(self, options, browser_type="generic"):
"""
Configure virtual display vs headless mode for any browser
:param options: Browser options object (ChromeOptions, FirefoxOptions, etc.)
:param browser_type: Type of browser for logging ("firefox", "chrome", "undetected-chrome")
:return: bool indicating if virtual display is being used
"""
use_virtual_display = self.config.get('selenium.use_virtual_display', False)
display_available = self.start_virtual_display() if use_virtual_display else False
if display_available:
self.selenium_log.debug(f"Using virtual display for {browser_type} (better anti-detection)")
return True
else:
self.selenium_log.warning(f"Using headless mode for {browser_type} (virtual display not available or disabled)")
# Set headless mode - different for different browsers
if hasattr(options, 'headless'):
options.headless = True
if hasattr(options, 'add_argument'):
options.add_argument('--headless')
return False
def start_virtual_display(self):
"""
Start virtual display using Xvfb for anti-detection
This makes browsers think they're running in a real display environment
:return:
"""
if not hasattr(self, 'xvfb_process') or self.xvfb_process is None:
try:
import subprocess
import os
# Check if DISPLAY environment variable is set
display = os.environ.get('DISPLAY', ':99')
# Check if Xvfb is already running on this display
try:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True, timeout=5)
if f'Xvfb {display}' in result.stdout:
self.selenium_log.debug(f"Xvfb already running on display {display}")
# Ensure DISPLAY is exported even if we didn't start Xvfb ourselves
os.environ['DISPLAY'] = display
self.xvfb_process = None # We didn't start it, so don't try to stop it
return True
except Exception:
pass
# Start Xvfb
width = os.environ.get('SCREEN_WIDTH', '1920')
height = os.environ.get('SCREEN_HEIGHT', '1080')
depth = os.environ.get('SCREEN_DEPTH', '24')
xvfb_cmd = [
'Xvfb', display,
'-screen', '0', f'{width}x{height}x{depth}',
'-ac', '+extension', 'GLX', '+render', '-noreset'
]
self.xvfb_process = subprocess.Popen(
xvfb_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setsid if hasattr(os, 'setsid') else None
)
# Wait a moment for Xvfb to start
time.sleep(1)
# Set DISPLAY environment variable for this process
os.environ['DISPLAY'] = display
self.selenium_log.debug(f"Started Xvfb on display {display} with resolution {width}x{height}x{depth}")
return True
except Exception as e:
self.selenium_log.warning(f"Failed to start virtual display: {e}. Falling back to headless mode.")
# Fall back to headless mode if Xvfb fails
self.xvfb_process = None
return False
def stop_virtual_display(self):
"""
Stop virtual display if we started it
"""
if hasattr(self, 'xvfb_process') and self.xvfb_process is not None:
try:
self.xvfb_process.terminate()
self.xvfb_process.wait(timeout=5)
self.selenium_log.debug("Stopped virtual display")
except Exception as e:
self.selenium_log.warning(f"Error stopping virtual display: {e}")
try:
self.xvfb_process.kill()
except Exception:
pass
finally:
self.xvfb_process = None
def get_user_agent(self):
"""
Get user agent for the browser
"""
# TODO: add input for agents to frontend/config
# Check out https://github.com/fake-useragent/fake-useragent
# ua = UserAgent(platforms='desktop', os=["Mac OS X", "Windows"], browsers="Firefox") for Firefox for example
if self.browser == "firefox":
agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0",
]
else:
raise NotImplementedError(f"User agent retrieval not implemented for browser type: {self.browser}")
return random.choice(agents)
def get_profile(self):
"""
Get the user profile for the browser if it exists. This is used to allow Selenium to use an existing profile.
Can be overridden by subclasses to provide a specific profile path.
"""
try:
# Determine active browser
browser = self.browser or self.config.get('selenium.browser')
path = None
if browser == 'firefox':
path = self.config.get('selenium.firefox_profile_path', None)
else:
raise NotImplementedError("Currently only Firefox is supported")
if not path:
return None
# Normalize env and relative paths
path = os.path.expanduser(os.path.expandvars(path))
if not os.path.isabs(path):
base = self.config.get('PATH_ROOT')
path = os.path.abspath(os.path.join(base, path))
if os.path.exists(path):
return path
else:
if hasattr(self, 'log') and self.log:
self.log.warning(f"Configured profile not found at {path}; ignoring")
self.selenium_log.warning(f"Configured profile not found at {path}; ignoring")
return None
except Exception as e:
if hasattr(self, 'log') and self.log:
self.log.warning(f"get_profile() error: {e}")
self.selenium_log.warning(f"get_profile() error: {e}")
return None
def _create_temp_profile(self):
"""
Create a fresh, isolated browser profile directory for this session.
The path is derived from PATH_DATA, the dataset key (if available) and the browser
type, so the directory name is predictable and easy to audit/clean up manually.
The caller is responsible for passing the path to the browser (e.g. via --profile).
Sets self._temp_profile_path and self._temp_profile_is_temp = True.
:return str: Absolute path to the created profile directory.
"""
# Build a human-readable, collision-resistant name
dataset_key = getattr(self.dataset, 'key', None) if hasattr(self, 'dataset') else None
browser = self.browser or 'firefox'
if dataset_key:
profile_name = f"{dataset_key}_{browser}_temp_profile"
else:
# Fallback: timestamp + pid so concurrent workers don't collide
import datetime
profile_name = f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}_{os.getpid()}_{browser}_temp_profile"
try:
base_dir = self.config.get('PATH_DATA')
profile_path = str(base_dir.joinpath(profile_name))
except Exception:
# Last resort: system temp dir
import tempfile
profile_path = os.path.join(tempfile.gettempdir(), profile_name)
os.makedirs(profile_path, exist_ok=True)
self._temp_profile_path = profile_path
self._temp_profile_is_temp = True
self.selenium_log.info(f"Created temporary Firefox profile: {profile_path}")
try:
if hasattr(self, 'dataset') and self.dataset:
self.dataset.log(f"Created temporary Firefox profile: {profile_path}")
except Exception:
pass
return profile_path
def _remove_temp_profile(self):
"""
Remove the temporary profile directory created by _create_temp_profile(), if any.
Only removes directories we created ourselves (self._temp_profile_is_temp == True).
User-provided profile paths are never deleted.
"""
if not self._temp_profile_is_temp or not self._temp_profile_path:
return
path = self._temp_profile_path
self._temp_profile_path = None
self._temp_profile_is_temp = False
if not os.path.exists(path):
return
try:
shutil.rmtree(path, ignore_errors=False)
self.selenium_log.info(f"Removed temporary Firefox profile: {path}")
except Exception as e:
# On Windows, Firefox may briefly hold file locks after quit(); retry once
self.selenium_log.warning(f"Could not remove temp profile on first attempt ({e}); retrying in 2s")
time.sleep(2)
shutil.rmtree(path, ignore_errors=True)
if not os.path.exists(path):
self.selenium_log.info(f"Removed temporary Firefox profile (retry): {path}")
else:
self.selenium_log.warning(f"Temp profile may still exist at {path}; manual cleanup may be needed")
def apply_common_driver_config(self):
"""
Apply common driver configuration after driver creation.
"""
if not self.driver:
return
# Apply timeouts from config
page_timeout = self.config.get('selenium.page_load_timeout', 60)
implicit_wait = self.config.get('selenium.implicit_wait', 10)
self.driver.set_page_load_timeout(page_timeout)
self.driver.implicitly_wait(implicit_wait)
# Set window size to common resolution; maximize if possible
self.driver.set_window_size(1920, 1080)
self.driver.maximize_window()
# Remove webdriver detection
self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
self.selenium_log.debug(f"Applied page load timeout: {page_timeout}s")
self.selenium_log.debug(f"Applied implicit wait: {implicit_wait}s")
def quit_selenium(self, kill_browser=False):
"""
Always attempt to close the browser otherwise multiple versions of Chrome will be left running.
And Chrome is a memory hungry monster.
"""
try:
self.driver.quit()
except Exception as e:
self.selenium_log.error(e)
self.driver = None
self.last_scraped_url = None
# Clear applied-cookie domain cache
try:
self._cookie_domains_applied = set()
except Exception:
pass
if kill_browser:
time.sleep(2)
self.kill_browser()
# Clear browser PID
self.browser_pid = None
# Stop virtual display (only if we started it)
self.stop_virtual_display()
# Remove temp profile if we created it for this session
self._remove_temp_profile()
def restart_selenium(self, eager=None, kill_browser=False):
"""
Weird Selenium error? Restart and try again.
"""
self.quit_selenium(kill_browser=kill_browser)
self.start_selenium(eager=eager)
self.reset_current_page()
def set_page_load_timeout(self, timeout=60):
"""
Adjust the time that Selenium will wait for a page to load before failing
"""
self.driver.set_page_load_timeout(timeout)
def check_for_movement(self, old_element=None, wait_time=5):
"""
Some driver.get() commands will not result in an error even if they do not result in updating the page source.
This can happen, for example, if a url directs the browser to attempt to download a file. It can therefore be
important to check and ensure a new page was actually obtained before retrieving the page source as you will
otherwise retrieve he same information from the previous url.
WARNING: It may also be true that a url redirects to the same url as previous scraped url. This check would assume no
movement occurred. Use in conjunction with self.reset_current_page() if it is necessary to check every url results
and identify redirects.
"""
if old_element:
# If an old element is provided, wait for it to become stale
try:
WebDriverWait(self.driver, wait_time).until(EC.staleness_of(old_element))
except (TimeoutException, ElementNotInteractableException, ElementClickInterceptedException) as e: