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
remove unneeded BuildDOMTreeEvent in favor of BrowserStateRequestEvent and private helper
Nick Sweeting0088b3e01644
diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex fc464ab38..beac74366 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -7,7 +7,6 @@ from typing import TYPE_CHECKINGfrom browser_use.browser.events import (BrowserErrorEvent,BrowserStateRequestEvent,- BuildDOMTreeEvent,ScreenshotEvent,)from browser_use.browser.watchdog_base import BaseWatchdog@@ -30,7 +29,7 @@ class DOMWatchdog(BaseWatchdog):helper methods for other watchdogs."""- LISTENS_TO = [BuildDOMTreeEvent, BrowserStateRequestEvent]+ LISTENS_TO = [BrowserStateRequestEvent]EMITS = [BrowserErrorEvent]# Public properties for other watchdogs@@ -111,16 +110,19 @@ class DOMWatchdog(BaseWatchdog):if event.include_dom:logger.debug('🌳 Building DOM tree...')- # Dispatch BuildDOMTreeEvent and wait for result- # The DOM watchdog will handle this and update our cached selector map- dom_event = self.event_bus.dispatch(- BuildDOMTreeEvent(- previous_state=self.browser_session._cached_browser_state_summary.dom_state- if self.browser_session._cached_browser_state_summary- else None- )+ # Build the DOM directly using the internal method+ previous_state = (+ self.browser_session._cached_browser_state_summary.dom_state+ if self.browser_session._cached_browser_state_summary+ else None)- content = await dom_event.event_result()++ try:+ # Call the DOM building method directly+ content = await self._build_dom_tree(previous_state)+ except Exception as e:+ logger.warning(f'DOM build failed: {e}, using minimal state')+ content = SerializedDOMState(_root=None, selector_map={})if not content:# Fallback to minimal DOM state@@ -215,15 +217,12 @@ class DOMWatchdog(BaseWatchdog):is_pdf_viewer=False,)- async def on_BuildDOMTreeEvent(self, event: BuildDOMTreeEvent) -> SerializedDOMState:- """Build and serialize DOM tree, returning ready-to-use LLM format.-- Updates public properties:- - self.selector_map: Index to node mapping for element access- - self.uuid_selector_map: UUID to node mapping for element access- - self.current_dom_state: Cached serialized state- - self.enhanced_dom_tree: Full enhanced DOM tree-+ async def _build_dom_tree(self, previous_state: SerializedDOMState | None = None) -> SerializedDOMState:+ """Internal method to build and serialize DOM tree.++ This is the actual implementation that does the work, called by both+ on_BrowserStateRequestEvent.+Returns:SerializedDOMState with serialized DOM and selector map"""@@ -240,11 +239,9 @@ class DOMWatchdog(BaseWatchdog):# Get serialized DOM tree using the servicestart = time.time()- print(f'DOMWatchdog: About to call get_serialized_dom_tree with dom_service={self._dom_service}')self.current_dom_state, self.enhanced_dom_tree, timing_info = await self._dom_service.get_serialized_dom_tree(previous_cached_state=event.previous_state)- print('DOMWatchdog: Returned from get_serialized_dom_tree')end = time.time()logger.debug(f'Time taken to get DOM tree: {end - start} seconds')@@ -298,8 +295,7 @@ class DOMWatchdog(BaseWatchdog):"""if not self.selector_map:# Build DOM if not cached- result = await self.event_bus.dispatch(BuildDOMTreeEvent())- await result+ await self._build_dom_tree()return self.selector_map.get(index) if self.selector_map else None@@ -313,8 +309,7 @@ class DOMWatchdog(BaseWatchdog):"""if not self.uuid_selector_map:# Build DOM if not cached- result = await self.event_bus.dispatch(BuildDOMTreeEvent())- await result+ await self._build_dom_tree()return self.uuid_selector_map.get(uuid) if self.uuid_selector_map else Nonediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex d89c8656f..c35aaf36d 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1321,10 +1321,13 @@ class BrowserSession(BaseModel):targets = await self.cdp_client.send.Target.getTargets()all_targets = targets.get('targetInfos', [])- # Check each target's frame tree+ # Check each target's frame tree (page and iframe targets)for target in all_targets:target_id = target.get('targetId')- if not target_id:+ target_type = target.get('type')++ # Skip non-page/iframe targets as they don't have frames+ if not target_id or target_type not in ['page', 'iframe']:continue# Attach to target to get frame tree@@ -1332,37 +1335,65 @@ class BrowserSession(BaseModel):session_id = session['sessionId']try:- # Enable Page domain first- await self.cdp_client.send.Page.enable(session_id=session_id)-- # Get the frame tree for this target- frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)-- # Check if frame_id exists in this target's frame tree- def frame_exists_in_tree(frame_node: dict) -> bool:- """Recursively check if frame_id exists in the frame tree."""- # Check current frame- if frame_node.get('frame', {}).get('id') == frame_id:- return True-- # Check child frames recursively- child_frames = frame_node.get('childFrames', [])- for child in child_frames:- if frame_exists_in_tree(child):+ if target_type == 'page':+ # For page targets, check the frame tree+ # Enable Page domain first (only works for page targets)+ await self.cdp_client.send.Page.enable(session_id=session_id)++ # Get the frame tree for this target+ frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)++ # Check if frame_id exists in this target's frame tree+ def frame_exists_in_tree(frame_node: dict) -> bool:+ """Recursively check if frame_id exists in the frame tree."""+ # Check current frame+ if frame_node.get('frame', {}).get('id') == frame_id:return True- return False-- # Check if the frame exists in this target's tree- if frame_exists_in_tree(frame_tree_result.get('frameTree', {})):- # Frame found! Keep the session attached and return a client for it- # Note: We're returning the cdp_client with the session already attached- # The caller is responsible for detaching when done- return self.cdp_client, session_id, target_id+ # Check child frames recursively+ child_frames = frame_node.get('childFrames', [])+ for child in child_frames:+ if frame_exists_in_tree(child):+ return True- finally:- # Detach from target if frame not found+ return False++ # Check if the frame exists in this target's tree+ if frame_exists_in_tree(frame_tree_result.get('frameTree', {})):+ # Frame found! Keep the session attached and return a client for it+ # Note: We're returning the cdp_client with the session already attached+ # The caller is responsible for detaching when done+ return self.cdp_client, session_id, target_id++ elif target_type == 'iframe':+ # For iframe targets (OOPIFs), the target itself IS the frame+ # We need to check if this iframe target's frame ID matches what we're looking for+ try:+ # Enable Page domain to get frame info+ await self.cdp_client.send.Page.enable(session_id=session_id)++ # Get the frame tree for this iframe target+ frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)++ # For an iframe target, the root frame IS the iframe itself+ iframe_frame_id = frame_tree_result.get('frameTree', {}).get('frame', {}).get('id')++ if iframe_frame_id == frame_id:+ # This is the iframe we're looking for!+ # Don't detach - caller is responsible for cleanup+ return self.cdp_client, session_id, target_id++ except Exception:+ # This iframe target doesn't match+ pass++ # If we didn't find the frame in this target, detach before trying next one+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})++ except Exception as e:+ # On error, make sure to detachawait self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+ raise# Frame not found in any targetraise ValueError(f"Frame with ID '{frame_id}' not found in any target")diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex db50caa15..ca518e235 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -61,33 +61,21 @@ class DomService:async def _get_targets_for_current_page(self) -> CurrentPageTargets:"""Get the target for the current page."""- print('DomService._get_targets_for_current_page: Getting targets...')targets = await self.browser_session.cdp_client.send.Target.getTargets()- print(f'DomService: Found {len(targets.get("targetInfos", []))} targets')# Use the current_target_id directlycurrent_target_id = self.browser_session.current_target_idif not current_target_id:raise ValueError('No current target ID set in browser session')- print(f'DomService: Looking for target with ID: {current_target_id}')-# Find main page target by IDmain_target = next((t for t in targets['targetInfos'] if t['targetId'] == current_target_id), None)if not main_target:- # Debug: print all available targets- print(f'DomService ERROR: No target found for current target ID: {current_target_id}')- print('Available targets:')- for t in targets['targetInfos']:- print(f' - {t["targetId"]}: type={t["type"]}, url={t.get("url", "none")}')raise ValueError(f'No target found for current target ID: {current_target_id}')- print(f'DomService: Found main target: type={main_target["type"]}, url={main_target.get("url", "none")}')-# Separate iframe targets for attachmentiframe_targets = [t for t in targets['targetInfos'] if t['type'] == 'iframe']- print(f'DomService: Found {len(iframe_targets)} iframe targets')return CurrentPageTargets(page_session=main_target,