Josedcape commited on
Commit
65cbdfa
verified
1 Parent(s): 8112baf

Update src/browser/custom_browser.py

Browse files
Files changed (1) hide show
  1. src/browser/custom_browser.py +115 -120
src/browser/custom_browser.py CHANGED
@@ -1,120 +1,115 @@
1
- import asyncio
2
- import pdb
3
-
4
- from playwright.async_api import Browser as PlaywrightBrowser
5
- from playwright.async_api import (
6
- BrowserContext as PlaywrightBrowserContext,
7
- )
8
- from playwright.async_api import (
9
- Playwright,
10
- async_playwright,
11
- )
12
- from browser_use.browser.browser import Browser
13
- from browser_use.browser.context import BrowserContext, BrowserContextConfig
14
- from playwright.async_api import BrowserContext as PlaywrightBrowserContext
15
- import logging
16
-
17
- from .custom_context import CustomBrowserContext
18
-
19
- logger = logging.getLogger(__name__)
20
-
21
- class CustomBrowser(Browser):
22
-
23
- async def new_context(
24
- self,
25
- config: BrowserContextConfig = BrowserContextConfig()
26
- ) -> CustomBrowserContext:
27
- return CustomBrowserContext(config=config, browser=self)
28
-
29
- async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
30
- """Sets up and returns a Playwright Browser instance with anti-detection measures."""
31
- if self.config.wss_url:
32
- browser = await playwright.chromium.connect(self.config.wss_url)
33
- return browser
34
- elif self.config.chrome_instance_path:
35
- import subprocess
36
-
37
- import requests
38
-
39
- try:
40
- # Check if browser is already running
41
- response = requests.get('http://localhost:9222/json/version', timeout=2)
42
- if response.status_code == 200:
43
- logger.info('Reusing existing Chrome instance')
44
- browser = await playwright.chromium.connect_over_cdp(
45
- endpoint_url='http://localhost:9222',
46
- timeout=20000, # 20 second timeout for connection
47
- )
48
- return browser
49
- except requests.ConnectionError:
50
- logger.debug('No existing Chrome instance found, starting a new one')
51
-
52
- # Start a new Chrome instance
53
- subprocess.Popen(
54
- [
55
- self.config.chrome_instance_path,
56
- '--remote-debugging-port=9222',
57
- ],
58
- stdout=subprocess.DEVNULL,
59
- stderr=subprocess.DEVNULL,
60
- )
61
-
62
- # Attempt to connect again after starting a new instance
63
- for _ in range(10):
64
- try:
65
- response = requests.get('http://localhost:9222/json/version', timeout=2)
66
- if response.status_code == 200:
67
- break
68
- except requests.ConnectionError:
69
- pass
70
- await asyncio.sleep(1)
71
-
72
- try:
73
- browser = await playwright.chromium.connect_over_cdp(
74
- endpoint_url='http://localhost:9222',
75
- timeout=20000, # 20 second timeout for connection
76
- )
77
- return browser
78
- except Exception as e:
79
- logger.error(f'Failed to start a new Chrome instance.: {str(e)}')
80
- raise RuntimeError(
81
- ' To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
82
- )
83
-
84
- else:
85
- try:
86
- disable_security_args = []
87
- if self.config.disable_security:
88
- disable_security_args = [
89
- '--disable-web-security',
90
- '--disable-site-isolation-trials',
91
- '--disable-features=IsolateOrigins,site-per-process',
92
- ]
93
-
94
- browser = await playwright.chromium.launch(
95
- headless=self.config.headless,
96
- args=[
97
- '--no-sandbox',
98
- '--disable-blink-features=AutomationControlled',
99
- '--disable-infobars',
100
- '--disable-background-timer-throttling',
101
- '--disable-popup-blocking',
102
- '--disable-backgrounding-occluded-windows',
103
- '--disable-renderer-backgrounding',
104
- '--disable-window-activation',
105
- '--disable-focus-on-load',
106
- '--no-first-run',
107
- '--no-default-browser-check',
108
- '--no-startup-window',
109
- '--window-position=0,0',
110
- # '--window-size=1280,1000',
111
- ]
112
- + disable_security_args
113
- + self.config.extra_chromium_args,
114
- proxy=self.config.proxy,
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()