Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
hotload page immediately based on url found in task
Nick Sweeting734e58a1fc02
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex b2371fcbb..ddd3a1c50 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -23,6 +23,7 @@ from browser_use.agent.cloud_events import (UpdateAgentTaskEvent,)from browser_use.agent.message_manager.utils import save_conversation+from browser_use.browser.events import BrowserStateRequestEventfrom browser_use.llm.base import BaseChatModelfrom browser_use.llm.messages import BaseMessage, UserMessagefrom browser_use.tokens.service import TokenCost@@ -698,7 +699,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.debug(f'π Step {self.state.n_steps}: Getting browser state...')browser_state_summary = await self.browser_session.get_browser_state_summary(- cache_clickable_elements_hashes=True, include_screenshot=self.settings.use_vision+ cache_clickable_elements_hashes=True, include_screenshot=self.settings.use_vision, cached=True,)# Check for new downloads after getting browser state (catches PDF auto-downloads and previous step downloads)@@ -1178,6 +1179,27 @@ class Agent(Generic[Context, AgentStructuredOutput]):return False, False+ def _extract_url_from_task(self, task: str) -> str | None:+ """Extract URL from task string using naive pattern matching."""+ import re++ # Look for common URL patterns+ patterns = [+ r'https?://[^\s<>"\']+', # Full URLs with http/https+ r'(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:/[^\s<>"\']*)?', # Domain names with optional paths+ ]++ for pattern in patterns:+ match = re.search(pattern, task)+ if match:+ url = match.group(0)+ # Add https:// if missing+ if not url.startswith(('http://', 'https://')):+ url = 'https://' + url+ return url++ return None+@observe(name='agent.run', metadata={'task': '{{task}}', 'debug': '{{debug}}'})@time_execution_async('--run')async def run(@@ -1234,12 +1256,23 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Start browser session and attach watchdogsassert self.browser_session is not None, 'Browser session must be initialized before starting'self.logger.debug('π Starting browser session...')- from browser_use.browser.events import BrowserStartEvent+ from browser_use.browser.events import BrowserStartEvent, NavigateToUrlEventevent = self.browser_session.event_bus.dispatch(BrowserStartEvent())await eventself.logger.debug('π§ Browser session started with watchdogs attached')++ # Check if task contains a URL and navigate to it immediately+ initial_url = self._extract_url_from_task(self.task)+ if initial_url:+ self.logger.info(f'π Found URL in task: {initial_url}, navigating immediately...')+ self.browser_session.event_bus.dispatch(NavigateToUrlEvent(url=initial_url))++ # this one is just for element higlighting as a loading animation, not technically used by anything but nice to see what the agent will see as the browser starts up+ self.browser_session.event_bus.dispatch(BrowserStateRequestEvent(include_dom=True, include_screenshot=True))++ self.logger.debug(f'β Navigated to {initial_url}')# Execute initial actions if providedif self.initial_actions:diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex 49e92770c..9e24167ba 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -1,6 +1,7 @@"""Default browser action handlers using CDP."""import asyncio+import platformfrom typing import TYPE_CHECKINGfrom browser_use.browser.events import (@@ -73,6 +74,10 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.info(f'π±οΈ {msg}')self.logger.debug(f'Element xpath: {element_node.xpath}')+ # Wait a bit for potential new tab to be created+ # This is necessary because tab creation is async and might not be immediate+ await asyncio.sleep(0.5)+# Check if a new tab was openedafter_target_ids = await self.browser_session._cdp_get_all_pages()if len(after_target_ids) > len(initial_target_ids):@@ -189,7 +194,8 @@ class DefaultActionWatchdog(BaseWatchdog):cdp_session = await self.browser_session.attach_cdp_session()# Get the correct session ID for the element's frame- session_id = await self._get_session_id_for_element(element_node)+ # session_id = await self._get_session_id_for_element(element_node)+ session_id = cdp_session.session_id# Get element boundsbackend_node_id = element_node.backend_node_id@@ -216,28 +222,32 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.debug(f'Failed to scroll element into view: {e}')# Set up download detection if downloads are enabled- download_path = None- download_event = asyncio.Event()- download_guid = None+ # download_path = None+ # download_event = asyncio.Event()+ # download_guid = None- if self.browser_session.browser_profile.downloads_path:+ if self.browser_session.browser_profile.downloads_path and expect_download:# Enable download eventsawait cdp_session.cdp_client.send.Page.setDownloadBehavior(params={'behavior': 'allow', 'downloadPath': str(self.browser_session.browser_profile.downloads_path)},session_id=session_id,)- # Set up download listener- async def on_download_will_begin(event):- nonlocal download_guid- download_guid = event['guid']- download_event.set()+ # # Set up download listener+ # async def on_download_will_begin(event):+ # nonlocal download_guid+ # download_guid = event['guid']+ # download_event.set()# TODO: fix this with download_watchdog.py# cdp_client.on('Page.downloadWillBegin', on_download_will_begin, session_id=session_id) # type: ignore[attr-defined]+# Perform the click using CDP+ # TODO: do occlusion detection first, if element is not on the top, fire JS-based+ # click event instead using xpath of x,y coordinate clicking, because we wont be able to click *through* occluding elements using x,y clickstry:+ self.logger.debug(f'π Dragging mouse over element before clicking x: {center_x}px y: {center_y}px ...')# Move mouse to elementawait cdp_session.cdp_client.send.Input.dispatchMouseEvent(params={@@ -247,8 +257,22 @@ class DefaultActionWatchdog(BaseWatchdog):},session_id=session_id,)+ await asyncio.sleep(0.123)++ # Calculate modifier bitmask for CDP+ # CDP Modifier bits: Alt=1, Control=2, Meta/Command=4, Shift=8+ modifiers = 0+ if new_tab:+ # Use platform-appropriate modifier for "open in new tab"+ if platform.system() == 'Darwin':+ modifiers = 4 # Meta/Cmd key+ self.logger.debug('β Using Cmd modifier for new tab click...')+ else:+ modifiers = 2 # Control key+ self.logger.debug('β Using Ctrl modifier for new tab click...')# Mouse down+ self.logger.debug(f'ππΎ Clicking x: {center_x}px y: {center_y}px with modifiers: {modifiers} ...')await cdp_session.cdp_client.send.Input.dispatchMouseEvent(params={'type': 'mousePressed',@@ -256,9 +280,11 @@ class DefaultActionWatchdog(BaseWatchdog):'y': center_y,'button': 'left','clickCount': 1,+ 'modifiers': modifiers,},session_id=session_id,)+ await asyncio.sleep(0.145)# Mouse upawait cdp_session.cdp_client.send.Input.dispatchMouseEvent(@@ -268,11 +294,12 @@ class DefaultActionWatchdog(BaseWatchdog):'y': center_y,'button': 'left','clickCount': 1,+ 'modifiers': modifiers,},session_id=session_id,)- # TODO: do occlusion detection, if element is not on the top, fire JS-based click event instead of x,y coordinate clicking+ self.logger.debug('π±οΈ Clicked successfully using x,y coordinates')# Handle download if expected: should be handled by downloads_watchdog.py now using browser-level download event listeners# if self.browser_session.browser_profile.downloads_path:@@ -311,6 +338,7 @@ class DefaultActionWatchdog(BaseWatchdog):# # Navigation is handled by NavigationWatchdog via events# return download_path+ # raise Exception('Quad click isnt perfect yet especially for multi-action sequences where navigation dropdowns move around, additional JavaScript click is needed')except Exception as e:self.logger.warning(f'CDP click failed: {type(e).__name__}: {e}')@@ -651,23 +679,27 @@ class DefaultActionWatchdog(BaseWatchdog):if '+' in keys:# Handle modifier keysparts = keys.split('+')- modifiers = 0key = parts[-1]-++ # Calculate modifier bits inline+ # CDP Modifier bits: Alt=1, Control=2, Meta/Command=4, Shift=8+ modifiers = 0for part in parts[:-1]:- if part in ['ctrl', 'control']:- modifiers |= 2 # Control- elif part in ['shift']:- modifiers |= 8 # Shift- elif part in ['alt', 'option']:+ part_lower = part.lower()+ if part_lower in ['alt', 'option']:modifiers |= 1 # Alt- elif part in ['cmd', 'command', 'meta']:+ elif part_lower in ['ctrl', 'control']:+ modifiers |= 2 # Control+ elif part_lower in ['meta', 'cmd', 'command']:modifiers |= 4 # Meta/Command+ elif part_lower in ['shift']:+ modifiers |= 8 # Shift# Send key with modifiers+ # Use rawKeyDown for non-text keys (like shortcuts)await cdp_session.cdp_client.send.Input.dispatchKeyEvent(params={- 'type': 'keyDown',+ 'type': 'rawKeyDown','key': key.capitalize() if len(key) == 1 else key,'modifiers': modifiers,},@@ -704,8 +736,12 @@ class DefaultActionWatchdog(BaseWatchdog):key = key_map.get(keys, keys)+ # Use rawKeyDown for special keys (non-text producing keys)+ # Use keyDown only for regular text characters+ key_type = 'rawKeyDown' if keys in key_map else 'keyDown'+await cdp_session.cdp_client.send.Input.dispatchKeyEvent(- params={'type': 'keyDown', 'key': key},+ params={'type': key_type, 'key': key},session_id=cdp_session.session_id,)await cdp_session.cdp_client.send.Input.dispatchKeyEvent(diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex d9f4e68c0..724ca38a5 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -9,6 +9,7 @@ from browser_use.browser.events import (BrowserStateRequestEvent,ScreenshotEvent,BrowserConnectedEvent,+ TabCreatedEvent,)from browser_use.browser.watchdog_base import BaseWatchdogfrom browser_use.dom.service import DomService@@ -30,7 +31,7 @@ class DOMWatchdog(BaseWatchdog):helper methods for other watchdogs."""- LISTENS_TO = [BrowserConnectedEvent, BrowserStateRequestEvent]+ LISTENS_TO = [TabCreatedEvent, BrowserStateRequestEvent]EMITS = [BrowserErrorEvent]# Public properties for other watchdogs@@ -42,7 +43,7 @@ class DOMWatchdog(BaseWatchdog):# Internal DOM service_dom_service: DomService | None = None- async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:+ async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:# self.logger.debug('Setting up init scripts in browser')self.logger.debug('π Injecting DOM Service init script to track event listeners added to DOM elements by JS...')@@ -113,8 +114,8 @@ class DOMWatchdog(BaseWatchdog):page_url = await self.browser_session.get_current_page_url()- # Check if this is a new tab or chrome:// target early for optimization- is_empty_page = is_new_tab_page(page_url) or page_url.startswith('chrome://')+ # check if we should skip DOM tree build for pointless pages+ not_a_meaningful_website = page_url.lower().split(':', 1)[0] not in ('http', 'https')# Get tabs info once at the beginning for all pathsself.logger.debug('Getting tabs info...')@@ -123,8 +124,8 @@ class DOMWatchdog(BaseWatchdog):try:# Fast path for empty pages- if is_empty_page:- self.logger.debug(f'β‘ Fast path for empty target: {page_url}')+ if not_a_meaningful_website:+ self.logger.debug(f'β‘ Skipping BuildDOMTree for empty target: {page_url}')# Create minimal DOM statecontent = SerializedDOMState(_root=None, selector_map={})@@ -150,7 +151,7 @@ class DOMWatchdog(BaseWatchdog):return BrowserStateSummary(dom_state=content,url=page_url,- title='New Tab' if is_new_tab_page(page_url) else 'Chrome Page',+ title='Empty Tab',tabs=tabs_info,screenshot=screenshot_b64,page_info=page_info,@@ -190,15 +191,15 @@ class DOMWatchdog(BaseWatchdog):screenshot_b64 = Noneif event.include_screenshot:try:- screenshot_event = self.event_bus.dispatch(ScreenshotEvent(full_page=False))+ screenshot_event = self.event_bus.dispatch(ScreenshotEvent(full_page=False, event_timeout=6.0))# Add timeout to prevent hanging if no handler exists- screenshot_result = await asyncio.wait_for(screenshot_event.event_result(), timeout=2.0)+ screenshot_result = await screenshot_event.event_results_flat_dict(raise_if_none=True, raise_if_any=True)if screenshot_result:screenshot_b64 = screenshot_result.get('screenshot')except TimeoutError:- self.logger.warning('Screenshot timed out after 2 seconds - no handler registered?')+ self.logger.warning('Screenshot timed out after 6 seconds - no handler registered or slow page?')except Exception as e:- self.logger.warning(f'Screenshot failed: {e}')+ self.logger.warning(f'Screenshot failed: {type(e).__name__}: {e}')# Tabs info already fetched at the beginning@@ -309,6 +310,9 @@ class DOMWatchdog(BaseWatchdog):# Update selector map for other watchdogsself.selector_map = self.current_dom_state.selector_map+ # Update BrowserSession's cached selector map+ if self.browser_session:+ self.browser_session.update_cached_selector_map(self.selector_map)# Inject highlighting for visual feedback if we have elementsif self.selector_map and self._dom_service:@@ -320,10 +324,6 @@ class DOMWatchdog(BaseWatchdog):except Exception as e:self.logger.debug(f'Failed to inject highlighting: {e}')- # Update BrowserSession's cached selector map- if self.browser_session:- self.browser_session.update_cached_selector_map(self.selector_map)-# Build UUID selector mapself.uuid_selector_map = {}if self.selector_map:diff --git a/browser_use/browser/screenshot_watchdog.py b/browser_use/browser/screenshot_watchdog.pyindex ff5c3795a..7751b86a1 100644--- a/browser_use/browser/screenshot_watchdog.py+++ b/browser_use/browser/screenshot_watchdog.py@@ -6,6 +6,7 @@ from bubus import BaseEventfrom browser_use.browser.events import ScreenshotEventfrom browser_use.browser.watchdog_base import BaseWatchdog+from cdp_use.cdp.page import CaptureScreenshotParametersif TYPE_CHECKING:pass@@ -34,18 +35,12 @@ class ScreenshotWatchdog(BaseWatchdog):cdp_session = await self.browser_session.attach_cdp_session()# Prepare screenshot parameters- params = {'format': 'png'}-- # if event.full_page:- # params['captureBeyondViewport'] = True-- # if event.clip:- # params['clip'] = event.clip+ params = CaptureScreenshotParameters(format='png', captureBeyondViewport=False)# Take screenshot using CDPself.logger.debug(f'[ScreenshotWatchdog] Taking screenshot with params: {params}')result = await cdp_session.cdp_client.send.Page.captureScreenshot(- # params=params,+ params=params,session_id=cdp_session.session_id)diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex f4eb13913..a6a23535c 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -68,7 +68,16 @@ class CDPSession(BaseModel):return await cdp_session.attach()async def attach(self) -> Self:- result = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.target_id, 'flatten': True})+ result = await self.cdp_client.send.Target.attachToTarget(+ params={+ 'targetId': self.target_id,+ 'flatten': True,+ 'filter': [ # type: ignore+ {'type': 'page', 'exclude': False},+ {'type': 'iframe', 'exclude': False},+ ],+ }+ )self.session_id = result['sessionId']# Enable all domains in parallel@@ -323,10 +332,14 @@ class BrowserSession(BaseModel):# ========== Helper Methods ==========async def get_browser_state_summary(- self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = False+ self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True, cached: bool = False) -> BrowserStateSummary:+ if cached and self._cached_browser_state_summary is not None and self._cached_browser_state_summary.dom_state:+ self.logger.debug('π Using pre-cached browser state summary for open tab')+ return self._cached_browser_state_summary+# Dispatch the event and wait for result- event = cast(+ event: BrowserStateRequestEvent = cast(BrowserStateRequestEvent,self.event_bus.dispatch(BrowserStateRequestEvent(@@ -810,12 +823,16 @@ class BrowserSession(BaseModel):return result.get('cookies', [])async def _cdp_set_cookies(self, cookies: list[Cookie]) -> None:- """Set cookies using CDP Network.setCookies."""+ """Set cookies using CDP Storage.setCookies."""if not self.cdp_session or not cookies:returncdp_session = await self.attach_cdp_session()- await cdp_session.cdp_client.send.Storage.setCookies(params={'cookies': cookies}, session_id=cdp_session.session_id)+ # Storage.setCookies expects params dict with 'cookies' key+ await cdp_session.cdp_client.send.Storage.setCookies(+ params={'cookies': cookies}, # type: ignore[arg-type]+ session_id=cdp_session.session_id+ )async def _cdp_clear_cookies(self) -> None:"""Clear all cookies using CDP Network.clearBrowserCookies."""diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.pyindex b3f4696f5..77b28ca63 100644--- a/browser_use/browser/watchdog_base.py+++ b/browser_use/browser/watchdog_base.py@@ -1,7 +1,7 @@"""Base watchdog class for browser monitoring components."""import inspect-from typing import TYPE_CHECKING, ClassVar+from typing import TYPE_CHECKING, Any, ClassVarfrom collections.abc import Iterablefrom bubus import BaseEvent, EventBus@@ -23,8 +23,8 @@ class BaseWatchdog(BaseModel):# Class variables to statically define the list of events relevant to each watchdog# (not enforced, just to make it easier to understand the code and debug watchdogs at runtime)- LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [] # Events this watchdog listens to- EMITS: ClassVar[list[type[BaseEvent]]] = [] # Events this watchdog emits+ LISTENS_TO: ClassVar[list[type[BaseEvent[Any]]]] = [] # Events this watchdog listens to+ EMITS: ClassVar[list[type[BaseEvent[Any]]]] = [] # Events this watchdog emits# Core dependenciesevent_bus: EventBus = Field()diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex fc050f61d..213545b3c 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -317,12 +317,9 @@ class Controller(Generic[Context]):cdp_session = await browser_session.attach_cdp_session()try:- # result = await client.send.DOM.getDocument(params={'pierce': True}, session_id=session_id)- # root_node_id = result['root']['nodeId']- # page_html_result = await client.send.DOM.getOuterHTML(params={'nodeId': 1}, session_id=session_id)page_html_result = await cdp_session.cdp_client.send.Page.captureSnapshot(params={'format': 'mhtml'}, session_id=cdp_session.session_id- ) # included OOPIF content automatically+ ) # includes OOPIF content automaticallyexcept TimeoutError:raise RuntimeError('Page content extraction timed out after 5 seconds')except Exception as e:@@ -330,6 +327,14 @@ class Controller(Generic[Context]):page_html = page_html_result['data']+ try:+ # strip large data:... base64 encoded images, fonts, css, etc. from mhtml captureSnapshot output+ page_html = re.sub(r'url\(\s*data:[^)]+\)', 'url()', page_html, flags=re.I)+ page_html = re.sub(r'(?P<q>["\'])data:[^"\']*(?P=q)', r'\g<q>\g<q>', page_html, flags=re.I)+ page_html = re.sub(r'\bdata:[^)\s>"\']+', '', page_html, flags=re.I)+ except Exception as e:+ logger.warning(f'Error stripping data:... blobs from page html while converting to markdown: {type(e).__name__}: {e}')+markdownify_func = partial(markdownify.markdownify, strip=strip)try: