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
fix missing page domain enable
Nick Sweeting8d5434392f40
diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex a260c9ec2..fc464ab38 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -19,7 +19,7 @@ from browser_use.dom.views import (from browser_use.utils import is_new_tab_page, loggerif TYPE_CHECKING:- from browser_use.browser.views import BrowserStateSummary, PageInfo, TabInfo+ from browser_use.browser.views import BrowserStateSummaryclass DOMWatchdog(BaseWatchdog):@@ -233,18 +233,18 @@ class DOMWatchdog(BaseWatchdog):await self.browser_session.remove_highlights()except Exception as e:logger.debug(f'Failed to remove existing highlights: {e}')-+# Create or reuse DOM serviceif self._dom_service is None:self._dom_service = DomService(browser_session=self.browser_session, logger=logger)# 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}")+ 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(f"DOMWatchdog: Returned from get_serialized_dom_tree")+ print('DOMWatchdog: Returned from get_serialized_dom_tree')end = time.time()logger.debug(f'Time taken to get DOM tree: {end - start} seconds')@@ -252,11 +252,12 @@ class DOMWatchdog(BaseWatchdog):# Update selector map for other watchdogsself.selector_map = self.current_dom_state.selector_map-+# Inject highlighting for visual feedback if we have elementsif self.selector_map and self._dom_service:try:from browser_use.dom.debug.highlights import inject_highlighting_script+await inject_highlighting_script(self._dom_service, self.selector_map)logger.debug(f'Injected highlighting for {len(self.selector_map)} elements')except Exception as e:diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 330335d3c..d89c8656f 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -91,7 +91,7 @@ class BrowserSession(BaseModel):# PDF handling_auto_download_pdfs: bool = PrivateAttr(default=True)-+def model_post_init(self, __context) -> None:"""Register event handlers after model initialization."""# Register BrowserSession's event handlers manually since it's not a BaseWatchdog@@ -150,7 +150,9 @@ class BrowserSession(BaseModel):def __str__(self) -> str:# Note: _original_browser_session tracking moved to Agent classport_number = (self.cdp_url or 'no-cdp').rsplit(':', 1)[-1].split('/', 1)[0]- return f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.current_target_id))[-2:]}'+ return (+ f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.current_target_id))[-2:]}'+ )async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> None:"""Handle browser start request."""@@ -225,7 +227,6 @@ class BrowserSession(BaseModel):))-# ========== Helper Methods ==========async def get_browser_state_with_recovery(@@ -470,10 +471,7 @@ class BrowserSession(BaseModel):try:# Use helper to get document titletitle_result = await asyncio.wait_for(- self._cdp_execute_on_target(- target_id,- commands=[('Runtime.evaluate', {'expression': 'document.title'})]- ),+ self._cdp_execute_on_target(target_id, commands=[('Runtime.evaluate', {'expression': 'document.title'})]),timeout=2.0,)title = title_result.get('result', {}).get('value', '') if title_result else ''@@ -804,10 +802,7 @@ class BrowserSession(BaseModel):async def frames_by_target(self, target_id: str) -> list[str]:"""Get all frame IDs for a target."""# Get frame tree using helper- frame_tree = await self._cdp_execute_on_target(- target_id,- commands=[('Page.getFrameTree', {})]- )+ frame_tree = await self._cdp_execute_on_target(target_id, commands=[('Page.getFrameTree', {})])# Extract frame IDs recursivelyframe_ids = []@@ -837,7 +832,6 @@ class BrowserSession(BaseModel):return None-async def get_current_page_cdp_session_id(self) -> str | None:"""Get the CDP session ID for the current page."""if not hasattr(self, 'current_target_id') or not self.current_target_id:@@ -895,12 +889,7 @@ class BrowserSession(BaseModel):# Enable necessary domainsawait cdp_client.send.Target.setAutoAttach(- params={- 'autoAttach': True,- 'waitForDebuggerOnStart': False,- 'flatten': True- },- session_id=session_id+ params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}, session_id=session_id)await asyncio.gather(@@ -1014,31 +1003,32 @@ class BrowserSession(BaseModel):"""Get info about the current active target using CDP."""if not self.current_target_id:return None-+targets = await self.cdp_client.send.Target.getTargets()for target in targets.get('targetInfos', []):if target.get('targetId') == self.current_target_id:return targetreturn None-+async def get_current_page_url(self) -> str:"""Get the URL of the current page using CDP."""target = await self.get_current_target_info()if target:return target.get('url', '')return ''-+async def get_current_page_title(self) -> str:"""Get the title of the current page using CDP."""if not self.current_target_id:return ''-+try:- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )session_id = session['sessionId']title_result = await self.cdp_client.send.Runtime.evaluate(- params={'expression': 'document.title'},- session_id=session_id+ params={'expression': 'document.title'}, session_id=session_id)title = title_result.get('result', {}).get('value', '')await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})@@ -1115,18 +1105,18 @@ class BrowserSession(BaseModel):async def get_selector_map(self) -> dict[int, 'EnhancedDOMTreeNode']:"""Get the current selector map from cached state or DOM watchdog.-+Returns:Dictionary mapping element indices to EnhancedDOMTreeNode objects"""# First try cached selector mapif self._cached_selector_map:return self._cached_selector_map-+# Try to get from DOM watchdogif self._dom_watchdog and hasattr(self._dom_watchdog, 'selector_map'):return self._dom_watchdog.selector_map or {}-+# Return empty dict if nothing availablereturn {}@@ -1139,18 +1129,15 @@ class BrowserSession(BaseModel):params={'targetId': self.current_target_id, 'flatten': True})session_id = session['sessionId']-+# Remove highlights via JavaScript - matches the highlighting system from debug/highlights.pyscript = """// Remove all browser-use highlight elementsconst highlights = document.querySelectorAll('[data-browser-use-highlight]');highlights.forEach(el => el.remove());"""- await self.cdp_client.send.Runtime.evaluate(- params={'expression': script},- session_id=session_id- )-+ await self.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)+# Detach from targetawait self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})except Exception as e:@@ -1161,32 +1148,34 @@ class BrowserSession(BaseModel):"""Get list of downloaded files from the downloads directory."""if not self.browser_profile.downloads_path:return []-+downloads_dir = Path(self.browser_profile.downloads_path)if not downloads_dir.exists():return []-+# Get all files in downloads directory (not directories)files = [str(f) for f in downloads_dir.iterdir() if f.is_file()]return sorted(files)# ========== CDP-based replacements for browser_context operations ==========- async def _cdp_execute_on_target(self, target_id: str, commands: list[tuple[str, dict]] | None = None, callable_fn: Any | None = None) -> Any:+ async def _cdp_execute_on_target(+ self, target_id: str, commands: list[tuple[str, dict]] | None = None, callable_fn: Any | None = None+ ) -> Any:"""Execute CDP commands on a specific target with automatic attach/detach.-+Args:target_id: The target ID to attach tocommands: List of (method, params) tuples to execute, e.g. [('Runtime.evaluate', {'expression': '...'})]callable_fn: Alternative - async function that receives (cdp_client, session_id) and returns result-+Returns:Result of the last command or callable_fn return value"""# Attach to targetsession = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']-+try:if callable_fn:# Execute the provided async function@@ -1221,9 +1210,7 @@ class BrowserSession(BaseModel):async def _cdp_create_new_page(self, url: str = 'about:blank') -> str:"""Create a new page/tab using CDP Target.createTarget. Returns target ID."""- result = await self.cdp_client.send.Target.createTarget(- params={'url': url, 'newWindow': False, 'background': False}- )+ result = await self.cdp_client.send.Target.createTarget(params={'url': url, 'newWindow': False, 'background': False})return result['targetId']async def _cdp_close_page(self, target_id: str) -> None:@@ -1301,7 +1288,7 @@ class BrowserSession(BaseModel):"""Navigate to URL using CDP Page.navigate."""# Use provided target_id or fall back to current_target_idtarget_to_use = target_id or self.current_target_id-+if not target_to_use:# If no target available, get the first page targettargets = await self._cdp_get_all_pages()@@ -1309,102 +1296,91 @@ class BrowserSession(BaseModel):target_to_use = targets[0]['targetId']self.current_target_id = target_to_useelse:- raise ValueError("No target available for navigation")-+ raise ValueError('No target available for navigation')+# Use helper to navigate on the target- await self._cdp_execute_on_target(- target_to_use,- commands=[- ('Page.enable', {}),- ('Page.navigate', {'url': url})- ]- )-+ await self._cdp_execute_on_target(target_to_use, commands=[('Page.enable', {}), ('Page.navigate', {'url': url})])+async def cdp_client_for_frame(self, frame_id: str) -> Any:"""Get a CDP client attached to the target containing the specified frame.-+Iterates through all targets, checks their frame trees to find which target- contains the frame with the given frame_id, then returns a CDP client+ contains the frame with the given frame_id, then returns a CDP clientattached to that target.-+Args:frame_id: The frame ID to search for-+Returns:CDP client attached to the target containing the frame-+Raises:ValueError: If the frame is not found in any target"""# Get all targetstargets = await self.cdp_client.send.Target.getTargets()all_targets = targets.get('targetInfos', [])-+# Check each target's frame treefor target in all_targets:target_id = target.get('targetId')if not target_id:continue-+# Attach to target to get frame tree- session = await self.cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )+ session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']-+try:- # Get the frame tree for this target- frame_tree_result = await self.cdp_client.send.Page.getFrameTree(- session_id=session_id- )+ # 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 treedef frame_exists_in_tree(frame_node: dict) -> bool:"""Recursively check if frame_id exists in the frame tree."""# Check current frameif frame_node.get('frame', {}).get('id') == frame_id:return True-+# Check child frames recursivelychild_frames = frame_node.get('childFrames', [])for child in child_frames:if frame_exists_in_tree(child):return True-+return False-+# Check if the frame exists in this target's treeif 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 donereturn self.cdp_client, session_id, target_id-+finally:# Detach from target if frame not found- await self.cdp_client.send.Target.detachFromTarget(- params={'sessionId': session_id}- )-+ await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+# Frame not found in any targetraise ValueError(f"Frame with ID '{frame_id}' not found in any target")-+async def cdp_client_for_target(self, target_id: str) -> Any:"""Get a CDP client attached to a specific target.-+This is a simpler helper that just attaches to a specific target ID.-+Args:target_id: The target ID to attach to-+Returns:Tuple of (cdp_client, session_id) for the attached target"""- session = await self.cdp_client.send.Target.attachToTarget(- params={'targetId': target_id, 'flatten': True}- )+ session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']-+# Return the client and session_id# Caller is responsible for detaching when donereturn self.cdp_client, session_iddiff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 6a854c0ce..db50caa15 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -61,33 +61,33 @@ class DomService:async def _get_targets_for_current_page(self) -> CurrentPageTargets:"""Get the target for the current page."""- print(f"DomService._get_targets_for_current_page: Getting targets...")+ 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")+ 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}")++ 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(f"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')}")+ 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')}")++ 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")+ print(f'DomService: Found {len(iframe_targets)} iframe targets')return CurrentPageTargets(page_session=main_target,@@ -98,7 +98,7 @@ class DomService:"""This function is cached, so go crazy"""target_id = str(target['targetId'])- print(f"DomService._attach_target: Attaching to target {target_id}, type={target.get('type')}")+ print(f'DomService._attach_target: Attaching to target {target_id}, type={target.get("type")}')# if target_id in self.target_to_session_id_cache:# return self.target_to_session_id_cache[target_id]@@ -108,27 +108,25 @@ class DomService:params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']- print(f"DomService: Successfully attached, got session_id={session_id}")+ print(f'DomService: Successfully attached, got session_id={session_id}')except Exception as e:- print(f"DomService ERROR: Failed to attach to target {target_id}: {e}")+ print(f'DomService ERROR: Failed to attach to target {target_id}: {e}')raise-+# Track this session for cleanupself._attached_sessions.add(session_id)- print(f"DomService: Enabling domains on session {session_id}...")+ print(f'DomService: Enabling domains on session {session_id}...')await self._enable_all_domains_on_session(session_id)- print(f"DomService: Domains enabled on session {session_id}")+ print(f'DomService: Domains enabled on session {session_id}')return session_id-+async def _cleanup_sessions(self) -> None:"""Detach from all attached sessions."""for session_id in self._attached_sessions:try:- await self.browser_session.cdp_client.send.Target.detachFromTarget(- params={'sessionId': session_id}- )+ await self.browser_session.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})except Exception:pass # Session might already be detachedself._attached_sessions.clear()@@ -319,21 +317,20 @@ class DomService:async def _get_all_trees_for_session_id(self, session_id: str) -> TargetAllTrees:if not self.browser_session.cdp_url:raise ValueError('CDP URL is not set')-- print(f"DomService._get_all_trees_for_session_id: Starting with session_id={session_id}")-++ print(f'DomService._get_all_trees_for_session_id: Starting with session_id={session_id}')+# Wait for the page to be ready firsttry:- print(f"DomService: Checking page ready state...")+ print('DomService: Checking page ready state...')ready_state = await self.browser_session.cdp_client.send.Runtime.evaluate(- params={'expression': 'document.readyState'},- session_id=session_id+ params={'expression': 'document.readyState'}, session_id=session_id)- print(f"DomService: Page ready state: {ready_state}")+ print(f'DomService: Page ready state: {ready_state}')except Exception as e:- print(f"Warning: Could not check page ready state: {e}")+ print(f'Warning: Could not check page ready state: {e}')- print(f"DomService: Creating CDP requests...")+ print('DomService: Creating CDP requests...')snapshot_request = self.browser_session.cdp_client.send.DOMSnapshot.captureSnapshot(params={'computedStyles': REQUIRED_COMPUTED_STYLES,@@ -356,24 +353,21 @@ class DomService:start = time.time()# Use wait_for with timeout to debug which call is hangingtry:- print(f"DomService: Gathering all CDP requests...")+ print('DomService: Gathering all CDP requests...')snapshot, dom_tree, ax_tree, device_pixel_ratio = await asyncio.wait_for(- asyncio.gather(- snapshot_request, dom_tree_request, ax_tree_request, device_pixel_ratio_request- ),- timeout=10.0+ asyncio.gather(snapshot_request, dom_tree_request, ax_tree_request, device_pixel_ratio_request), timeout=10.0)- print(f"DomService: All CDP requests completed successfully")- except asyncio.TimeoutError:- print("ERROR: CDP calls timed out in _get_all_trees_for_session_id")+ print('DomService: All CDP requests completed successfully')+ except TimeoutError:+ print('ERROR: CDP calls timed out in _get_all_trees_for_session_id')# Try to get them individually to see which one hangs- print("Trying snapshot...")+ print('Trying snapshot...')snapshot = await asyncio.wait_for(snapshot_request, timeout=2.0)- print("Trying dom_tree...")+ print('Trying dom_tree...')dom_tree = await asyncio.wait_for(dom_tree_request, timeout=2.0)- print("Trying ax_tree...")+ print('Trying ax_tree...')ax_tree = await asyncio.wait_for(ax_tree_request, timeout=2.0)- print("Trying device_pixel_ratio...")+ print('Trying device_pixel_ratio...')device_pixel_ratio = await asyncio.wait_for(device_pixel_ratio_request, timeout=2.0)end = time.time()cdp_timing = {'cdp_calls_total': end - start}@@ -585,13 +579,13 @@ class DomService:"""try:- print(f"DomService: Getting targets for current page...")+ print('DomService: Getting targets for current page...')page_session_info = await self._get_targets_for_current_page()- print(f"DomService: Got page session info, target_id={page_session_info.page_session.get('targetId')}")-- print(f"DomService: Getting DOM tree...")+ print(f'DomService: Got page session info, target_id={page_session_info.page_session.get("targetId")}')++ print('DomService: Getting DOM tree...')enhanced_dom_tree = await self.get_dom_tree(page_session_info.page_session)- print(f"DomService: Got enhanced DOM tree")+ print('DomService: Got enhanced DOM tree')start = time.time()serialized_dom_state, serializer_timing = DOMTreeSerializer(@@ -606,7 +600,7 @@ class DomService:all_timing = {**serializer_timing, **serialize_total_timing}return serialized_dom_state, enhanced_dom_tree, all_timing-+finally:# Cleanup any attached sessionsawait self._cleanup_sessions()