Update src/browser/custom_browser.py
Browse files- src/browser/custom_browser.py +115 -120
src/browser/custom_browser.py
CHANGED
|
@@ -1,120 +1,115 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 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 |
-
return browser
|
| 118 |
-
except Exception as e:
|
| 119 |
-
logger.error(f'Failed to initialize Playwright browser: {str(e)}')
|
| 120 |
-
raise
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import subprocess
|
| 4 |
+
import requests
|
| 5 |
+
from selenium import webdriver
|
| 6 |
+
from selenium.webdriver.chrome.options import Options
|
| 7 |
+
from selenium.webdriver.chrome.service import Service
|
| 8 |
+
from webdriver_manager.chrome import ChromeDriverManager
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
class CustomBrowser:
|
| 13 |
+
def __init__(self, config=None):
|
| 14 |
+
self.config = config or {}
|
| 15 |
+
self.driver = None
|
| 16 |
+
|
| 17 |
+
async def new_context(self):
|
| 18 |
+
"""Crea y retorna un nuevo contexto de navegador."""
|
| 19 |
+
return await self._setup_browser()
|
| 20 |
+
|
| 21 |
+
async def _setup_browser(self):
|
| 22 |
+
"""Configura y retorna una instancia de Selenium WebDriver con medidas anti-detecci贸n."""
|
| 23 |
+
chrome_options = Options()
|
| 24 |
+
|
| 25 |
+
# Configuraci贸n para modo headless (sin interfaz gr谩fica)
|
| 26 |
+
if self.config.get("headless", True):
|
| 27 |
+
chrome_options.add_argument("--headless=new")
|
| 28 |
+
|
| 29 |
+
# Configuraci贸n de seguridad
|
| 30 |
+
if self.config.get("disable_security", False):
|
| 31 |
+
chrome_options.add_argument("--disable-web-security")
|
| 32 |
+
chrome_options.add_argument("--disable-site-isolation-trials")
|
| 33 |
+
chrome_options.add_argument("--disable-features=IsolateOrigins,site-per-process")
|
| 34 |
+
|
| 35 |
+
# Argumentos adicionales de Chromium
|
| 36 |
+
chrome_options.add_argument("--no-sandbox")
|
| 37 |
+
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
|
| 38 |
+
chrome_options.add_argument("--disable-infobars")
|
| 39 |
+
chrome_options.add_argument("--disable-background-timer-throttling")
|
| 40 |
+
chrome_options.add_argument("--disable-popup-blocking")
|
| 41 |
+
chrome_options.add_argument("--disable-backgrounding-occluded-windows")
|
| 42 |
+
chrome_options.add_argument("--disable-renderer-backgrounding")
|
| 43 |
+
chrome_options.add_argument("--disable-window-activation")
|
| 44 |
+
chrome_options.add_argument("--disable-focus-on-load")
|
| 45 |
+
chrome_options.add_argument("--no-first-run")
|
| 46 |
+
chrome_options.add_argument("--no-default-browser-check")
|
| 47 |
+
chrome_options.add_argument("--no-startup-window")
|
| 48 |
+
chrome_options.add_argument("--window-position=0,0")
|
| 49 |
+
|
| 50 |
+
# Proxy (si est谩 configurado)
|
| 51 |
+
if self.config.get("proxy"):
|
| 52 |
+
chrome_options.add_argument(f"--proxy-server={self.config['proxy']}")
|
| 53 |
+
|
| 54 |
+
# Conexi贸n a una instancia de Chrome en ejecuci贸n (si se especifica)
|
| 55 |
+
if self.config.get("wss_url"):
|
| 56 |
+
chrome_options.debugger_address = self.config["wss_url"]
|
| 57 |
+
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
|
| 58 |
+
return self.driver
|
| 59 |
+
|
| 60 |
+
# Conexi贸n a una instancia local de Chrome (debug mode)
|
| 61 |
+
elif self.config.get("chrome_instance_path"):
|
| 62 |
+
try:
|
| 63 |
+
# Verifica si Chrome ya est谩 en ejecuci贸n
|
| 64 |
+
response = requests.get('http://localhost:9222/json/version', timeout=2)
|
| 65 |
+
if response.status_code == 200:
|
| 66 |
+
logger.info('Reusing existing Chrome instance')
|
| 67 |
+
chrome_options.debugger_address = "localhost:9222"
|
| 68 |
+
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
|
| 69 |
+
return self.driver
|
| 70 |
+
except requests.ConnectionError:
|
| 71 |
+
logger.debug('No existing Chrome instance found, starting a new one')
|
| 72 |
+
|
| 73 |
+
# Inicia una nueva instancia de Chrome
|
| 74 |
+
subprocess.Popen(
|
| 75 |
+
[
|
| 76 |
+
self.config["chrome_instance_path"],
|
| 77 |
+
'--remote-debugging-port=9222',
|
| 78 |
+
],
|
| 79 |
+
stdout=subprocess.DEVNULL,
|
| 80 |
+
stderr=subprocess.DEVNULL,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Intenta conectarse despu茅s de iniciar la instancia
|
| 84 |
+
for _ in range(10):
|
| 85 |
+
try:
|
| 86 |
+
response = requests.get('http://localhost:9222/json/version', timeout=2)
|
| 87 |
+
if response.status_code == 200:
|
| 88 |
+
break
|
| 89 |
+
except requests.ConnectionError:
|
| 90 |
+
pass
|
| 91 |
+
await asyncio.sleep(1)
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
chrome_options.debugger_address = "localhost:9222"
|
| 95 |
+
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
|
| 96 |
+
return self.driver
|
| 97 |
+
except Exception as e:
|
| 98 |
+
logger.error(f'Failed to start a new Chrome instance: {str(e)}')
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
'To start Chrome in Debug mode, close all existing Chrome instances and try again.'
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Inicia una nueva instancia de Chrome sin conexi贸n a una instancia existente
|
| 104 |
+
else:
|
| 105 |
+
try:
|
| 106 |
+
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
|
| 107 |
+
return self.driver
|
| 108 |
+
except Exception as e:
|
| 109 |
+
logger.error(f'Failed to initialize Selenium browser: {str(e)}')
|
| 110 |
+
raise
|
| 111 |
+
|
| 112 |
+
async def close(self):
|
| 113 |
+
"""Cierra el navegador."""
|
| 114 |
+
if self.driver:
|
| 115 |
+
self.driver.quit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|