-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser_fetch.py
More file actions
2052 lines (1710 loc) · 72.1 KB
/
browser_fetch.py
File metadata and controls
2052 lines (1710 loc) · 72.1 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
"""
browser_fetch.py
Unified browser interface for web scraping that automatically switches between
Selenium and Playwright based on a global configuration variable.
This module provides a consistent API regardless of which browser engine is used,
making it easy to switch between Selenium and Playwright without changing
application code.
Author: LinuxReport System
License: See LICENSE file
"""
# =============================================================================
# STANDARD LIBRARY IMPORTS
# =============================================================================
import time
import threading
import atexit
import signal
import sys
from datetime import datetime, timezone
from urllib.parse import urljoin, urlparse
# =============================================================================
# THIRD-PARTY IMPORTS
# =============================================================================
import random
import re
import requests
from bs4 import BeautifulSoup
# =============================================================================
# LOCAL IMPORTS
# =============================================================================
from shared import g_cs, CUSTOM_FETCH_CONFIG, g_logger, WORKER_PROXYING, PROXY_SERVER, PROXY_USERNAME, PROXY_PASSWORD, USE_PLAYWRIGHT
from app_config import FetchConfig
# =============================================================================
# SHARED CONSTANTS
# =============================================================================
# Network operation timeouts - for HTTP requests and element waiting
NETWORK_TIMEOUT = 20 # 20 seconds for HTTP requests and browser operations
# Thread synchronization timeout - for coordinating fetch operations
FETCH_LOCK_TIMEOUT = 30 # 30 seconds for acquiring fetch lock (longer due to thread coordination)
# Unified browser operation timeouts
BROWSER_TIMEOUT = 30 # 30 seconds for browser operations (page load, script execution)
BROWSER_WAIT_TIMEOUT = 25 # 25 seconds for waiting for elements
# =============================================================================
# SHARED BROWSER MANAGEMENT
# =============================================================================
class SharedBrowserManager:
"""
Base class for managing browser instances with common patterns.
Provides shared functionality for both Selenium and Playwright browser management,
including lock management, instance validation, and cleanup operations.
"""
_instances = {} # Will be overridden by subclasses
_lock = threading.Lock()
_fetch_lock = threading.Lock()
def __init__(self, use_tor, user_agent):
"""
Initialize a new browser manager instance.
Args:
use_tor (bool): Whether to use Tor proxy
user_agent (str): User agent string for the browser
"""
self.use_tor = use_tor
self.user_agent = user_agent
self.last_used = time.time()
@classmethod
def acquire_fetch_lock(cls):
"""
Acquire the fetch lock to synchronize fetch operations.
Ensures only one fetch operation can run at a time to prevent
resource conflicts and rate limiting issues.
Returns:
bool: True if lock was acquired successfully
"""
try:
return cls._fetch_lock.acquire(timeout=FETCH_LOCK_TIMEOUT)
except Exception as e:
g_logger.error(f"Error acquiring fetch lock: {e}")
return False
@classmethod
def release_fetch_lock(cls):
"""
Release the fetch lock after fetch operation is complete.
Safely releases the fetch lock, handling cases where the lock
may not have been acquired.
"""
try:
cls._fetch_lock.release()
except RuntimeError:
# Lock was not acquired, ignore
pass
@classmethod
def force_cleanup(cls):
"""
Force shutdown and cleanup of all browser instances.
"""
g_logger.info("Forcing browser cleanup...")
with cls._lock:
cls._cleanup_all_instances()
g_logger.info("Force cleanup completed")
@classmethod
def _cleanup_all_instances(cls):
"""
Clean up all browser instances safely.
Must be implemented by subclasses.
"""
raise NotImplementedError("Subclasses must implement _cleanup_all_instances")
@classmethod
def _is_instance_valid(cls, instance, use_tor, user_agent):
"""
Check if the current browser instance is valid for the given configuration.
Args:
instance: Browser instance to validate
use_tor (bool): Required Tor configuration
user_agent (str): Required user agent string
Returns:
bool: True if current instance matches configuration
"""
try:
# Only reuse if config matches
if not (instance and
instance.use_tor == use_tor and
instance.user_agent == user_agent):
return False
# Check if instance is still responsive
return instance.is_valid()
except Exception as e:
g_logger.error(f"Error during instance validation: {e}")
return False
# =============================================================================
# UNIFIED BROWSER INTERFACE
# =============================================================================
class BrowserInterface:
"""
Unified interface for browser operations that both Selenium and Playwright can implement.
This provides a consistent API regardless of the underlying browser engine.
"""
def __init__(self, use_tor, user_agent):
self.use_tor = use_tor
self.user_agent = user_agent
self.last_used = time.time()
def get_page_content(self, url):
"""
Navigate to URL and return page content.
Args:
url (str): URL to navigate to
Returns:
tuple: (page_content, status_code) where page_content is the HTML content
and status_code is the HTTP status
"""
raise NotImplementedError("Subclasses must implement get_page_content")
def find_elements(self, selector):
"""
Find elements matching the given CSS selector.
Args:
selector (str): CSS selector to find elements
Returns:
list: List of elements matching the selector
"""
raise NotImplementedError("Subclasses must implement find_elements")
def wait_for_elements(self, selector, timeout=None):
"""
Wait for elements matching the selector to appear.
Args:
selector (str): CSS selector to wait for
timeout (float, optional): Timeout in seconds
Returns:
bool: True if elements found, False if timeout
"""
raise NotImplementedError("Subclasses must implement wait_for_elements")
def close(self):
"""Close the browser instance."""
raise NotImplementedError("Subclasses must implement close")
def is_valid(self):
"""
Check if the browser instance is still valid and responsive.
Returns:
bool: True if browser is valid, False otherwise
"""
raise NotImplementedError("Subclasses must implement is_valid")
class SeleniumBrowserWrapper(BrowserInterface):
"""
Wrapper for Selenium WebDriver that implements the unified BrowserInterface.
"""
def __init__(self, driver, use_tor, user_agent):
super().__init__(use_tor, user_agent)
self.driver = driver
def get_page_content(self, url):
"""Navigate to URL and return page content using Selenium."""
try:
self.driver.get(url)
return self.driver.page_source, 200
except Exception as e:
g_logger.error(f"Selenium navigation error: {e}")
return "", 500
def find_elements(self, selector):
"""Find elements using Selenium."""
try:
from selenium.webdriver.common.by import By
return self.driver.find_elements(By.CSS_SELECTOR, selector)
except Exception as e:
g_logger.error(f"Selenium find elements error: {e}")
return []
def wait_for_elements(self, selector, timeout=None):
"""Wait for elements using Selenium."""
try:
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
if timeout is None:
timeout = BROWSER_WAIT_TIMEOUT
WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located((By.CSS_SELECTOR, selector))
)
return True
except Exception as e:
g_logger.debug(f"Selenium wait for elements timeout: {e}")
return False
def close(self):
"""Close Selenium driver."""
try:
self.driver.quit()
except Exception as e:
g_logger.error(f"Error closing Selenium driver: {e}")
def is_valid(self):
"""Check if Selenium driver is valid."""
try:
self.driver.execute_script("return document.readyState;")
return True
except Exception:
return False
class PlaywrightBrowserWrapper(BrowserInterface):
"""
Wrapper for Playwright browser that implements the unified BrowserInterface.
"""
def __init__(self, browser, context, use_tor, user_agent):
super().__init__(use_tor, user_agent)
self.browser = browser
self.context = context
self.page = None
def get_page_content(self, url):
"""Navigate to URL and return page content using Playwright."""
try:
self.page = self.context.new_page()
self.page.goto(url, timeout=BROWSER_TIMEOUT * 1000) # Playwright uses milliseconds
return self.page.content(), 200
except Exception as e:
g_logger.error(f"Playwright navigation error: {e}")
return "", 500
def find_elements(self, selector):
"""Find elements using Playwright."""
try:
if self.page:
return self.page.locator(selector).all()
return []
except Exception as e:
g_logger.error(f"Playwright find elements error: {e}")
return []
def wait_for_elements(self, selector, timeout=None):
"""Wait for elements using Playwright."""
try:
if timeout is None:
timeout = BROWSER_WAIT_TIMEOUT
if self.page:
self.page.wait_for_selector(selector, timeout=int(timeout * 1000)) # Playwright uses milliseconds
return True
return False
except Exception as e:
g_logger.debug(f"Playwright wait for elements timeout: {e}")
return False
def close(self):
"""Close Playwright page and context."""
try:
if self.page:
self.page.close()
if self.context:
self.context.close()
except Exception as e:
g_logger.error(f"Error closing Playwright browser: {e}")
def is_valid(self):
"""Check if Playwright context is valid."""
try:
if self.context:
pages = self.context.pages
return True
return False
except Exception:
return False
# =============================================================================
# UNIFIED BROWSER CREATION
# =============================================================================
def get_common_browser_args(use_tor, user_agent):
"""
Get common browser arguments for both Selenium and Playwright.
Args:
use_tor (bool): Whether to use Tor proxy
user_agent (str): User agent string
Returns:
dict: Common browser configuration arguments
"""
return {
'anti_detection': [
"--disable-blink-features=AutomationControlled",
"--disable-extensions",
"--disable-plugins",
"--disable-images", # Speed up loading
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--disable-features=TranslateUI",
"--disable-ipc-flooding-protection",
"--memory-pressure-off",
"--max-old-space-size=4096", # Limit memory usage
"--window-size=1920,1080", # Consistent window size
],
'performance': [
"--disable-gpu",
"--no-sandbox",
"--disable-dev-shm-usage",
],
'proxy': get_proxy_config(use_tor),
'user_agent': user_agent,
'viewport': {"width": 1920, "height": 1080},
'locale': "en-US",
'timezone_id': "America/New_York",
'geolocation': None,
'permissions': [],
}
def get_proxy_config(use_tor):
"""
Get proxy configuration for browser.
Args:
use_tor (bool): Whether to use Tor proxy
Returns:
dict or None: Proxy configuration
"""
if use_tor:
return {"server": "socks5://127.0.0.1:9050"}
return None
def get_common_context_options(use_tor, user_agent):
"""
Get common context options for Playwright.
Args:
use_tor (bool): Whether to use Tor proxy
user_agent (str): User agent string
Returns:
dict: Common context options
"""
args = get_common_browser_args(use_tor, user_agent)
return {
"user_agent": args['user_agent'],
"viewport": args['viewport'],
"ignore_https_errors": True,
"java_script_enabled": True,
"locale": args['locale'],
"timezone_id": args['timezone_id'],
"geolocation": args['geolocation'],
"permissions": args['permissions'],
"proxy": args['proxy'],
}
def get_common_chrome_options(use_tor, user_agent):
"""
Get common Chrome options for Selenium.
Args:
use_tor (bool): Whether to use Tor proxy
user_agent (str): User agent string
Returns:
list: Chrome arguments
"""
args = get_common_browser_args(use_tor, user_agent)
chrome_args = [
"--headless",
f"--user-agent={args['user_agent']}",
]
# Add all anti-detection and performance arguments
chrome_args.extend(args['anti_detection'])
chrome_args.extend(args['performance'])
# Add proxy if needed
if args['proxy']:
chrome_args.append(f"--proxy-server={args['proxy']['server']}")
return chrome_args
# =============================================================================
# UNIFIED ELEMENT EXTRACTION
# =============================================================================
class ElementExtractor:
"""
Unified element extraction interface for different browser engines.
Provides a consistent API for finding elements, getting attributes,
and extracting text content regardless of the underlying browser engine.
"""
def find_element(self, parent, selector):
"""
Find a single element matching the selector.
Args:
parent: Parent element to search within
selector (str): CSS selector to find
Returns:
Element or None: Found element or None if not found
"""
raise NotImplementedError("Subclasses must implement find_element")
def find_elements(self, parent, selector):
"""
Find all elements matching the selector.
Args:
parent: Parent element to search within
selector (str): CSS selector to find
Returns:
list: List of found elements
"""
raise NotImplementedError("Subclasses must implement find_elements")
def get_attribute(self, element, attr):
"""
Get an attribute value from an element.
Args:
element: Element to get attribute from
attr (str): Attribute name
Returns:
str or None: Attribute value or None if not found
"""
raise NotImplementedError("Subclasses must implement get_attribute")
def get_text(self, element):
"""
Get text content from an element.
Args:
element: Element to get text from
Returns:
str: Text content
"""
raise NotImplementedError("Subclasses must implement get_text")
def log_debugging_info(self, element, context):
"""
Log debugging information for failed element extraction.
Args:
element: The element being processed
context (str): Context for the debugging info
"""
try:
# Show what text content is available for debugging
all_text = self.get_text(element)
all_text = all_text[:200] + "..." if len(all_text) > 200 else all_text
g_logger.info(f"Available text content for {context}: {all_text}")
# Show available links for debugging
try:
links = self.find_elements(element, 'a')
links_info = []
for link in links[:3]:
href = self.get_attribute(link, 'href')
links_info.append(href or 'NO_HREF')
g_logger.info(f"Available links for {context}: {links_info}")
except Exception as link_error:
g_logger.debug(f"Error getting link info for {context}: {link_error}")
except Exception as debug_e:
g_logger.debug(f"Error during debug output for {context}: {debug_e}")
class SeleniumElementExtractor(ElementExtractor):
"""Selenium-specific element extractor implementation."""
def find_element(self, parent, selector):
"""Find element using Selenium."""
try:
from selenium.webdriver.common.by import By
return parent.find_element(By.CSS_SELECTOR, selector)
except Exception:
return None
def find_elements(self, parent, selector):
"""Find elements using Selenium."""
try:
from selenium.webdriver.common.by import By
return parent.find_elements(By.CSS_SELECTOR, selector)
except Exception:
return []
def get_attribute(self, element, attr):
"""Get attribute using Selenium."""
try:
return element.get_attribute(attr)
except Exception:
return None
def get_text(self, element):
"""Get text using Selenium."""
try:
return element.text
except Exception:
return ""
class PlaywrightElementExtractor(ElementExtractor):
"""Playwright-specific element extractor implementation."""
def find_element(self, parent, selector):
"""Find element using Playwright."""
try:
return parent.locator(selector).first
except Exception:
return None
def find_elements(self, parent, selector):
"""Find elements using Playwright."""
try:
return parent.locator(selector).all()
except Exception:
return []
def get_attribute(self, element, attr):
"""Get attribute using Playwright."""
try:
return element.get_attribute(attr)
except Exception:
return None
def get_text(self, element):
"""Get text using Playwright."""
try:
return element.text_content()
except Exception:
return ""
class BeautifulSoupElementExtractor(ElementExtractor):
"""BeautifulSoup-specific element extractor implementation."""
def find_element(self, parent, selector):
"""Find element using BeautifulSoup."""
try:
return parent.select_one(selector)
except Exception:
return None
def find_elements(self, parent, selector):
"""Find elements using BeautifulSoup."""
try:
return parent.select(selector)
except Exception:
return []
def get_attribute(self, element, attr):
"""Get attribute using BeautifulSoup."""
try:
if attr == "text":
return element.get_text().strip()
return element.get(attr)
except Exception:
return None
def get_text(self, element):
"""Get text using BeautifulSoup."""
try:
return element.get_text().strip()
except Exception:
return ""
# =============================================================================
# SHARED UTILITY FUNCTIONS
# =============================================================================
def extract_base_domain(url):
"""
Extract the base domain from a URL for configuration lookup.
Handles subdomains by extracting the main domain (e.g., example.com from sub.example.com).
Args:
url (str): The URL to parse
Returns:
str: Base domain for configuration lookup
"""
parsed = urlparse(url)
# Extract base domain (e.g., bandcamp.com from rocksteadydisco.bandcamp.com)
domain_parts = parsed.netloc.split('.')
if len(domain_parts) > 2:
# Handle subdomains like www.example.com or sub.example.co.uk
# This logic might need adjustment for complex TLDs like .co.uk
# For now, assume simple cases like example.com or sub.example.com
base_domain = '.'.join(domain_parts[-2:])
else:
base_domain = parsed.netloc
return base_domain
def get_site_config(url):
"""
Get the configuration for a given URL.
Looks up configuration in CUSTOM_FETCH_CONFIG using both base domain and full netloc.
Args:
url (str): URL to get configuration for
Returns:
tuple: (config, base_domain) where config is site-specific configuration or None
"""
base_domain = extract_base_domain(url)
parsed = urlparse(url)
# Always try base domain first, then fallback to netloc (for legacy configs)
config = CUSTOM_FETCH_CONFIG.get(base_domain)
if not config:
config = CUSTOM_FETCH_CONFIG.get(parsed.netloc)
# Special case for keithcu.com RSS feed
if not config and "keithcu.com" in base_domain:
config = FetchConfig(
needs_selenium=True, # Using browser for testing purposes
needs_tor=False,
post_container="pre", # RSS feeds in browser are wrapped in <pre> tags
title_selector="title",
link_selector="link",
link_attr="text", # RSS links are text content, not href attributes
filter_pattern="",
use_random_user_agent=False,
published_selector=None
)
return config, base_domain
# =============================================================================
# CENTRALIZED SITE CONFIGURATION MANAGEMENT
# =============================================================================
class SiteConfigManager:
"""
Centralized site configuration management.
Provides a single place to manage all site-specific configurations,
including special cases and custom configurations.
"""
@staticmethod
def get_keithcu_rss_config():
"""
Get configuration for keithcu.com RSS feed.
Returns:
FetchConfig: Configuration for keithcu.com RSS feed
"""
return FetchConfig(
needs_selenium=True, # Using browser for testing purposes
needs_tor=False,
post_container="pre", # RSS feeds in browser are wrapped in <pre> tags
title_selector="title",
link_selector="link",
link_attr="text", # RSS links are text content, not href attributes
filter_pattern="",
use_random_user_agent=False,
published_selector=None
)
@staticmethod
def get_enhanced_site_config(url):
"""
Get enhanced site configuration with better caching and special cases.
Args:
url (str): URL to get configuration for
Returns:
tuple: (config, base_domain) where config is site-specific configuration or None
"""
base_domain = extract_base_domain(url)
parsed = urlparse(url)
# Always try base domain first, then fallback to netloc (for legacy configs)
config = CUSTOM_FETCH_CONFIG.get(base_domain)
if not config:
config = CUSTOM_FETCH_CONFIG.get(parsed.netloc)
# Special case for keithcu.com RSS feed
if not config and "keithcu.com" in base_domain:
config = SiteConfigManager.get_keithcu_rss_config()
return config, base_domain
@staticmethod
def validate_config(config):
"""
Validate a site configuration.
Args:
config: Configuration to validate
Returns:
bool: True if configuration is valid
"""
if not config:
return False
required_fields = ['post_container', 'title_selector', 'link_selector']
for field in required_fields:
if not hasattr(config, field) or not getattr(config, field):
g_logger.warning(f"Configuration missing required field: {field}")
return False
return True
# =============================================================================
# UNIFIED ERROR HANDLING
# =============================================================================
class BrowserErrorHandler:
"""
Centralized error handling for browser operations.
Provides consistent error handling, logging, and recovery strategies
across all browser automation operations.
"""
@staticmethod
def handle_navigation_error(e, url):
"""
Handle navigation errors with consistent logging and recovery.
Args:
e (Exception): The navigation error
url (str): URL that failed to navigate to
Returns:
tuple: (status_code, error_message)
"""
error_msg = f"Navigation error for {url}: {e}"
g_logger.error(error_msg)
# Determine appropriate status code based on error type
if "timeout" in str(e).lower():
return 408, "Navigation timeout"
elif "connection" in str(e).lower():
return 503, "Connection error"
elif "not found" in str(e).lower():
return 404, "Page not found"
else:
return 500, "Navigation failed"
@staticmethod
def handle_element_error(e, context):
"""
Handle element extraction errors with consistent logging.
Args:
e (Exception): The element extraction error
context (str): Context where the error occurred
Returns:
str: Error message for logging
"""
error_msg = f"Element extraction error in {context}: {e}"
g_logger.error(error_msg)
return error_msg
@staticmethod
def handle_timeout_error(e, operation):
"""
Handle timeout errors with consistent logging.
Args:
e (Exception): The timeout error
operation (str): Operation that timed out
Returns:
str: Error message for logging
"""
error_msg = f"Timeout during {operation}: {e}"
g_logger.warning(error_msg)
return error_msg
@staticmethod
def handle_request_error(e, url):
"""
Handle HTTP request errors with consistent logging.
Args:
e (Exception): The request error
url (str): URL that failed
Returns:
tuple: (status_code, error_message)
"""
error_msg = f"Request error for {url}: {e}"
g_logger.error(error_msg)
# Determine appropriate status code based on error type
if hasattr(e, 'response') and e.response is not None:
return e.response.status_code, f"HTTP {e.response.status_code}"
elif "timeout" in str(e).lower():
return 408, "Request timeout"
elif "connection" in str(e).lower():
return 503, "Connection error"
else:
return 500, "Request failed"
@staticmethod
def log_operation_result(operation, url, success, details=None):
"""
Log operation results consistently.
Args:
operation (str): Operation performed
url (str): URL operated on
success (bool): Whether operation succeeded
details (str, optional): Additional details
"""
status = "SUCCESS" if success else "FAILED"
message = f"{operation} {status} for {url}"
if details:
message += f": {details}"
if success:
g_logger.info(message)
else:
g_logger.error(message)
# =============================================================================
# CENTRALIZED CLEANUP MANAGEMENT
# =============================================================================
class BrowserCleanupManager:
"""
Centralized cleanup management for all browser instances.
Provides unified cleanup handling for both Selenium and Playwright browsers,
including signal handling and graceful shutdown procedures.
"""
_cleanup_registered = False
@classmethod
def register_cleanup_handlers(cls):
"""
Register cleanup handlers for graceful shutdown.
This method should be called once during application initialization.
"""
if cls._cleanup_registered:
return
try:
# Register atexit handler for normal program termination
atexit.register(cls._atexit_handler)
g_logger.debug("Registered atexit cleanup handler")
# Note: Signal handlers are commented out since code runs under Apache/mod_wsgi
# mod_wsgi already handles SIGTERM and SIGINT, so registration is ignored
# signal.signal(signal.SIGTERM, cls._signal_handler)
# signal.signal(signal.SIGINT, cls._signal_handler)
cls._cleanup_registered = True
g_logger.info("Browser cleanup handlers registered successfully")
except Exception as e:
g_logger.error(f"Error registering cleanup handlers: {e}")
@classmethod
def cleanup_all_browsers(cls):
"""
Clean up all browser instances from both Selenium and Playwright.
This method ensures all browser resources are properly released.
"""
g_logger.info("Starting cleanup of all browser instances...")
try:
# Clean up Selenium drivers
try:
import seleniumfetch
seleniumfetch.SharedSeleniumDriver.force_cleanup()
g_logger.debug("Selenium drivers cleaned up")
except (ImportError, AttributeError) as e:
g_logger.debug(f"Selenium cleanup skipped: {e}")
# Clean up Playwright browsers
try:
import playwrightfetch
playwrightfetch.SharedPlaywrightBrowser.force_cleanup()
g_logger.debug("Playwright browsers cleaned up")
except (ImportError, AttributeError) as e:
g_logger.debug(f"Playwright cleanup skipped: {e}")
g_logger.info("All browser instances cleaned up successfully")
except Exception as e:
g_logger.error(f"Error during browser cleanup: {e}")
@classmethod
def _atexit_handler(cls):
"""
Atexit handler for cleanup on normal program termination.
"""
g_logger.info("Program exiting, cleaning up all browsers...")
cls.cleanup_all_browsers()
@classmethod
def _signal_handler(cls, signum, frame):
"""
Signal handler for graceful shutdown.
"""
g_logger.info(f"Received signal {signum}, cleaning up browsers...")
cls.cleanup_all_browsers()
sys.exit(0)
# =============================================================================
# COMMON UTILITY FUNCTIONS
# =============================================================================
class BrowserUtils:
"""
Common browser utility functions.