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
started migration to pure cdp
Gregor Žunič7bf17064f6f2
diff --git a/browser_use/__init__.py b/browser_use/__init__.pyindex 14d3df6c2..1635b1e79 100644--- a/browser_use/__init__.py+++ b/browser_use/__init__.py@@ -18,8 +18,7 @@ from browser_use.agent.service import Agentfrom browser_use.agent.views import ActionModel, ActionResult, AgentHistoryListfrom browser_use.browser import Browser, BrowserConfig, BrowserContext, BrowserContextConfig, BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controller--# from browser_use.dom.service import DomService+from browser_use.dom.service import DomServicefrom browser_use.llm import (ChatAnthropic,ChatAzureOpenAI,@@ -58,7 +57,7 @@ __all__ = ['BrowserSession','BrowserProfile','Controller',- # 'DomService',+ 'DomService','SystemPrompt','ActionResult','ActionModel',diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex fccda50b8..264555f15 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -129,7 +129,7 @@ class AgentMessagePrompt:@observe_debug(name='_get_browser_state_description')def _get_browser_state_description(self) -> str:- elements_text = self.browser_state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)+ elements_text = self.browser_state.dom_state.llm_representation(include_attributes=self.include_attributes)if len(elements_text) > self.max_clickable_elements_length:elements_text = elements_text[: self.max_clickable_elements_length]diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 28b5e2646..81f2d8e5c 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -21,7 +21,6 @@ from browser_use.agent.cloud_events import (CreateAgentTaskEvent,UpdateAgentTaskEvent,)-from browser_use.dom.serializer import DEFAULT_INCLUDE_ATTRIBUTESfrom browser_use.llm.base import BaseChatModelfrom browser_use.llm.messages import BaseMessage, UserMessagefrom browser_use.tokens.service import TokenCost@@ -150,7 +149,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):message_context: str | None = None,generate_gif: bool | str = False,available_file_paths: list[str] | None = None,- include_attributes: list[str] = DEFAULT_INCLUDE_ATTRIBUTES,+ include_attributes: list[str] | None = None,max_actions_per_step: int = 10,use_thinking: bool = True,max_history_items: int = 40,@@ -898,7 +897,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):"""Create and store history item"""if model_output:- interacted_elements = AgentHistory.get_interacted_element(model_output, browser_state_summary.selector_map)+ interacted_elements = AgentHistory.get_interacted_element(model_output, browser_state_summary.dom_state.selector_map)else:interacted_elements = [None]@@ -957,10 +956,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.debug(f'🤖 Browser-Use Library Version {self.version} ({self.source})')- def _log_step_context(self, current_page, browser_state_summary) -> None:+ def _log_step_context(self, current_page: Page, browser_state_summary: BrowserStateSummary) -> None:"""Log step context information"""url_short = current_page.url[:50] + '...' if len(current_page.url) > 50 else current_page.url- interactive_count = len(browser_state_summary.selector_map) if browser_state_summary else 0+ interactive_count = len(browser_state_summary.dom_state.selector_map) if browser_state_summary else 0self.logger.info(f'📍 Step {self.state.n_steps}: Evaluating page with {interactive_count} interactive elements on: {url_short}')@@ -1314,7 +1313,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):assert self.browser_session is not None, 'BrowserSession is not set up'cached_selector_map = await self.browser_session.get_selector_map()- cached_path_hashes = {e.hash.branch_path_hash for e in cached_selector_map.values()}+ cached_element_hashes = {hash(e) for e in cached_selector_map.values()}await self.browser_session.remove_highlights()@@ -1327,13 +1326,14 @@ class Agent(Generic[Context, AgentStructuredOutput]):if action.get_index() is not None and i != 0:new_browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)- new_selector_map = new_browser_state_summary.selector_map+ new_selector_map = new_browser_state_summary.dom_state.selector_map# Detect index change after previous actionorig_target = cached_selector_map.get(action.get_index()) # type: ignore- orig_target_hash = orig_target.hash.branch_path_hash if orig_target else None+ orig_target_hash = hash(orig_target) if orig_target else Nonenew_target = new_selector_map.get(action.get_index()) # type: ignore- new_target_hash = new_target.hash.branch_path_hash if new_target else None+ new_target_hash = hash(new_target) if new_target else None+if orig_target_hash != new_target_hash:msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'logger.info(msg)@@ -1346,8 +1346,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):)break- new_path_hashes = {e.hash.branch_path_hash for e in new_selector_map.values()}- if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):+ new_element_hashes = {hash(e) for e in new_selector_map.values()}+ if check_for_new_elements and not new_element_hashes.issubset(cached_element_hashes):# next action requires index but there are new elements on the pagemsg = f'Something new appeared after action {i} / {len(actions)}, following actions are NOT executed and should be retried.'logger.info(msg)@@ -1493,20 +1493,27 @@ class Agent(Generic[Context, AgentStructuredOutput]):Update action indices based on current page state.Returns updated action or None if element cannot be found."""- if not historical_element or not browser_state_summary.element_tree:+ if not historical_element or not browser_state_summary.dom_state.selector_map:return action- current_element = HistoryTreeProcessor.find_history_element_in_tree(- historical_element, browser_state_summary.element_tree+ # selector_hash_map = {hash(e): e for e in browser_state_summary.dom_state.selector_map.values()}++ highlight_index, current_element = next(+ (+ (highlight_index, element)+ for highlight_index, element in browser_state_summary.dom_state.selector_map.items()+ if element.element_hash == historical_element.element_hash+ ),+ (None, None),)- if not current_element or current_element.highlight_index is None:+ if not current_element or highlight_index is None:return Noneold_index = action.get_index()- if old_index != current_element.highlight_index:- action.set_index(current_element.highlight_index)- self.logger.info(f'Element moved in DOM, updated index from {old_index} to {current_element.highlight_index}')+ if old_index != highlight_index:+ action.set_index(highlight_index)+ self.logger.info(f'Element moved in DOM, updated index from {old_index} to {highlight_index}')return actiondiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex da01f9550..d1f7f1e03 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -14,6 +14,7 @@ from uuid_extensions import uuid7strfrom browser_use.agent.message_manager.views import MessageManagerStatefrom browser_use.browser.views import BrowserStateHistoryfrom browser_use.controller.registry.views import ActionModel+from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES, DOMInteractedElement, DOMSelectorMap# from browser_use.dom.history_tree_processor.service import (# DOMElementNode,@@ -41,18 +42,7 @@ class AgentSettings(BaseModel):available_file_paths: list[str] | None = Noneoverride_system_message: str | None = Noneextend_system_message: str | None = None- include_attributes: list[str] = [- 'title',- 'type',- 'name',- 'role',- 'tabindex',- 'aria-label',- 'placeholder',- 'value',- 'alt',- 'aria-expanded',- ]+ include_attributes: list[str] | None = DEFAULT_INCLUDE_ATTRIBUTESmax_actions_per_step: int = 10use_thinking: bool = Truemax_history_items: int = 40@@ -228,13 +218,13 @@ class AgentHistory(BaseModel):model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())@staticmethod- def get_interacted_element(model_output: AgentOutput, selector_map: SelectorMap) -> list[DOMHistoryElement | None]:+ def get_interacted_element(model_output: AgentOutput, selector_map: DOMSelectorMap) -> list[DOMInteractedElement | None]:elements = []for action in model_output.action:index = action.get_index()if index is not None and index in selector_map:- el: DOMElementNode = selector_map[index]- elements.append(HistoryTreeProcessor.convert_dom_element_to_history_element(el))+ el = selector_map[index]+ elements.append(DOMInteractedElement.load_from_enhanced_dom_tree(el))else:elements.append(None)return elementsdiff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex db94fec13..267d04d31 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -17,7 +17,8 @@ from typing import Any, Selffrom urllib.parse import urlparsefrom browser_use.config import CONFIG-from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode+from browser_use.dom.service import DomService+from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, SerializedDOMStatefrom browser_use.observability import observe_debugfrom browser_use.utils import _log_pretty_path, _log_pretty_url@@ -225,7 +226,7 @@ class BrowserSession(BaseModel):)_cached_browser_state_summary: BrowserStateSummary | None = PrivateAttr(default=None)- _cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)+ # _cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)_tab_visibility_callback: Any = PrivateAttr(default=None)_logger: logging.Logger | None = PrivateAttr(default=None)_downloaded_files: list[str] = PrivateAttr(default_factory=list)@@ -1968,33 +1969,14 @@ class BrowserSession(BaseModel):@retry(timeout=10, retries=0)async def remove_highlights(self):"""+ DEPRECATED+Removes all highlight overlays and labels created by the highlightElement function.Handles cases where the page might be closed or inaccessible.- """- page = await self.get_current_page()- try:- await page.evaluate(- """- try {- // Remove the highlight container and all its contents- const container = document.getElementById('playwright-highlight-container');- if (container) {- container.remove();- }- // Remove highlight attributes from elements- const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');- highlightedElements.forEach(el => {- el.removeAttribute('browser-user-highlight-id');- });- } catch (e) {- console.error('Failed to remove highlights:', e);- }- """- )- except Exception as e:- self.logger.debug(f'⚠️ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')- # Don't raise the error since this is not critical functionality+ TODO: this function has been deprecated, we will create new debug method+ """+ return@require_initializationasync def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:@@ -2092,11 +2074,13 @@ class BrowserSession(BaseModel):# Final fallback - try clicking by coordinates if availableif element_node.snapshot_node and element_node.snapshot_node.clientRects:try:+ # TODO: instead of using the cached center, we should use the actual center of the element (easy, just get it by nodeBackendId)self.logger.warning(- f'⚠️ Element click failed, falling back to coordinate click at ({element_node.viewport_coordinates.center.x}, {element_node.viewport_coordinates.center.y})'+ f'⚠️ Element click failed, falling back to coordinate click at ({element_node.snapshot_node.clientRects.center.x}, {element_node.snapshot_node.clientRects.center.y})')await page.mouse.click(- element_node.viewport_coordinates.center.x, element_node.viewport_coordinates.center.y+ element_node.snapshot_node.clientRects.center.x,+ element_node.snapshot_node.clientRects.center.y,)try:await page.wait_for_load_state()@@ -2885,26 +2869,6 @@ class BrowserSession(BaseModel):await self._wait_for_page_and_frames_load()updated_state = await self._get_updated_state()- # Find out which elements are new- # Do this only if url has not changed- if cache_clickable_elements_hashes:- # if we are on the same url as the last state, we can use the cached hashes- if self._cached_clickable_element_hashes and self._cached_clickable_element_hashes.url == updated_state.url:- # Pointers, feel free to edit in place- updated_state_clickable_elements = ClickableElementProcessor.get_clickable_elements(updated_state.element_tree)-- for dom_element in updated_state_clickable_elements:- dom_element.is_new = (- ClickableElementProcessor.hash_dom_element(dom_element)- not in self._cached_clickable_element_hashes.hashes # see which elements are new from the last state where we cached the hashes- )- # in any case, we need to cache the new hashes- self._cached_clickable_element_hashes = CachedClickableElementHashes(- url=updated_state.url,- hashes=ClickableElementProcessor.get_clickable_elements_hashes(updated_state.element_tree),- )-- assert updated_stateself._cached_browser_state_summary = updated_statereturn self._cached_browser_state_summary@@ -2915,7 +2879,6 @@ class BrowserSession(BaseModel):async def get_minimal_state_summary(self) -> BrowserStateSummary:"""Get basic page info without DOM processing, but try to capture screenshot"""from browser_use.browser.views import BrowserStateSummary- from browser_use.dom.views import DOMElementNodepage = await self.get_current_page()@@ -2936,19 +2899,8 @@ class BrowserSession(BaseModel):except Exception:tabs_info = []- # Create minimal DOM element for error state- minimal_element_tree = DOMElementNode(- tag_name='body',- xpath='/body',- attributes={},- children=[],- is_visible=True,- parent=None,- )-return BrowserStateSummary(- element_tree=minimal_element_tree, # Minimal DOM tree- selector_map={}, # Empty selector map+ dom_state=SerializedDOMState(_root=None, selector_map={}),url=url,title=title,tabs=tabs_info,@@ -2976,36 +2928,26 @@ class BrowserSession(BaseModel):self.logger.debug('🧹 Removing highlights...')await self.remove_highlights()self.logger.debug('🌳 Starting DOM processing...')- dom_service = DomService(page, logger=self.logger)- try:- content = await asyncio.wait_for(- dom_service.get_clickable_elements(- focus_element=focus_element,- viewport_expansion=self.browser_profile.viewport_expansion,- highlight_elements=self.browser_profile.highlight_elements,- ),- timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages- )- self.logger.debug('✅ DOM processing completed')- except TimeoutError:- self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')- self.logger.warning('🔄 Falling back to minimal DOM state to allow basic navigation...')-- # Create minimal DOM state for basic navigation- from browser_use.dom.views import DOMElementNode-- minimal_element_tree = DOMElementNode(- tag_name='body',- xpath='/body',- attributes={},- children=[],- is_visible=True,- parent=None,- )+ async with DomService(self, page) as dom_service:+ try:+ dom_state = await asyncio.wait_for(+ dom_service.get_serialized_dom_tree(+ previous_cached_state=self._cached_browser_state_summary.dom_state+ if self._cached_browser_state_summary+ else None,+ ),+ timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages+ )+ self.logger.debug('✅ DOM processing completed')+ except TimeoutError:+ self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')+ self.logger.warning('🔄 Falling back to minimal DOM state to allow basic navigation...')++ # Create minimal DOM state for basic navigation- from browser_use.dom.views import DOMState+ from browser_use.dom.views import SerializedDOMState- content = DOMState(element_tree=minimal_element_tree, selector_map={})+ dom_state = SerializedDOMState(_root=None, selector_map={})self.logger.debug('📋 Getting tabs info...')tabs_info = await self.get_tabs_info()@@ -3058,14 +3000,13 @@ class BrowserSession(BaseModel):# Check if this is a minimal fallback statebrowser_errors = []- if not content.selector_map: # Empty selector map indicates fallback state+ if not dom_state.selector_map: # Empty selector map indicates fallback statebrowser_errors.append(f'DOM processing timed out for {page.url} - using minimal state. Basic navigation still available via go_to_url, scroll, and search actions.')self.browser_state_summary = BrowserStateSummary(- element_tree=content.element_tree,- selector_map=content.selector_map,+ dom_state=dom_state,url=page.url,title=title,tabs=tabs_info,@@ -3216,7 +3157,7 @@ class BrowserSession(BaseModel):@classmethod@time_execution_sync('--enhanced_css_selector_for_element')- def _enhanced_css_selector_for_element(cls, element: DOMElementNode, include_dynamic_attributes: bool = True) -> str:+ def _enhanced_css_selector_for_element(cls, element: EnhancedDOMTreeNode, include_dynamic_attributes: bool = True) -> str:"""Creates a CSS selector for a DOM element, handling various edge cases and special characters.@@ -3320,9 +3261,8 @@ class BrowserSession(BaseModel):return css_selectorexcept Exception:- # Fallback to a more basic selector if something goes wrong- tag_name = element.tag_name or '*'- return f"{tag_name}[highlight_index='{element.highlight_index}']"+ # Fallback: use XPath as a CSS selector (via Playwright's "xpath=" pseudo-selector)+ return f'xpath={element.xpath or "//" + (element.tag_name or "*")}'@require_initialization@time_execution_async('--is_visible')@@ -3342,12 +3282,12 @@ class BrowserSession(BaseModel):@require_initialization@time_execution_async('--get_locate_element')- async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:+ async def get_locate_element(self, element: EnhancedDOMTreeNode) -> ElementHandle | None:page = await self.get_current_page()current_frame = page# Start with the target element and collect all parents- parents: list[DOMElementNode] = []+ parents: list[EnhancedDOMTreeNode] = []current = elementwhile current.parent is not None:parent = current.parent@@ -3513,7 +3453,7 @@ class BrowserSession(BaseModel):@require_initialization@time_execution_async('--input_text_element_node')- async def _input_text_element_node(self, element_node: DOMElementNode, text: str):+ async def _input_text_element_node(self, element_node: EnhancedDOMTreeNode, text: str):"""Input text into an element with proper error handling and state management.Handles different types of input fields and ensures proper element state before input.@@ -3576,7 +3516,7 @@ class BrowserSession(BaseModel):self.logger.debug(f'❌ Failed to input text into element: {repr(element_node)} on page {page_url}: {type(e).__name__}: {e}')- raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')+ raise BrowserError(f'Failed to input text into element: {repr(element_node)}')@require_initialization@time_execution_async('--switch_to_tab')@@ -3726,7 +3666,7 @@ class BrowserSession(BaseModel):async def get_selector_map(self) -> DOMSelectorMap:if self._cached_browser_state_summary is None:return {}- return self._cached_browser_state_summary.selector_map+ return self._cached_browser_state_summary.dom_state.selector_map@observe_debug(name='get_element_by_index')@require_initialization@@ -3746,17 +3686,13 @@ class BrowserSession(BaseModel):return False@staticmethod- def is_file_input(node: DOMElementNode) -> bool:- return (- isinstance(node, DOMElementNode)- and getattr(node, 'tag_name', '').lower() == 'input'- and node.attributes.get('type', '').lower() == 'file'- )+ def is_file_input(node: EnhancedDOMTreeNode) -> bool:+ return node.tag_name == 'input' and node.attributes.get('type', '').lower() == 'file'@require_initializationasync def find_file_upload_element_by_index(self, index: int, max_height: int = 3, max_descendant_depth: int = 3- ) -> DOMElementNode | None:+ ) -> EnhancedDOMTreeNode | None:"""Find the closest file input to the selected element by traversing the DOM bottom-up.At each level (up to max_height ancestors):@@ -3772,12 +3708,12 @@ class BrowserSession(BaseModel):candidate_element = selector_map[index]- def find_file_input_in_descendants(node: DOMElementNode, depth: int) -> DOMElementNode | None:- if depth < 0 or not isinstance(node, DOMElementNode):+ def find_file_input_in_descendants(node: EnhancedDOMTreeNode, depth: int) -> EnhancedDOMTreeNode | None:+ if depth < 0 or not isinstance(node, EnhancedDOMTreeNode):return Noneif self.is_file_input(node):return node- for child in getattr(node, 'children', []):+ for child in node.children:result = find_file_input_in_descendants(child, depth - 1)if result:return result@@ -3793,9 +3729,9 @@ class BrowserSession(BaseModel):if result:return result# 3. Check all siblings and their descendants- parent = getattr(current, 'parent', None)+ parent = current.parentif parent:- for sibling in getattr(parent, 'children', []):+ for sibling in parent.children:if sibling is current:continueif self.is_file_input(sibling):diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex cd1635267..b67725f81 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -3,7 +3,7 @@ from typing import Anyfrom pydantic import BaseModel-from browser_use.dom.views import DOMInteractedElement, DOMState+from browser_use.dom.views import DOMInteractedElement, SerializedDOMState# Pydantic@@ -41,12 +41,11 @@ class PageInfo(BaseModel):@dataclass-class BrowserStateSummary(DOMState):+class BrowserStateSummary:"""The summary of the browser's current state designed for an LLM to process"""- # provided by DOMState:- # element_tree: DOMElementNode- # selector_map: SelectorMap+ # provided by SerializedDOMState:+ dom_state: SerializedDOMStateurl: strtitle: strdiff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex d59384c67..d6fa00fb2 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -48,7 +48,7 @@ class Registry(Generic[Context]):'browser_session': BrowserSession,'browser': BrowserSession, # legacy name'browser_context': BrowserSession, # legacy name- 'page': Page,+ 'page': Page, # type: ignore'page_extraction_llm': BaseChatModel,'available_file_paths': list,'has_sensitive_data': bool,diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex ebc0f3c1a..9f18c5dbf 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -183,7 +183,7 @@ class Controller(Generic[Context]):msg = f'Downloaded file to {download_path}'else:emoji = '🖱️'- msg = f'Clicked button with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'+ msg = f'Clicked button with index {params.index}: {element_node.llm_representation()}'logger.info(f'{emoji} {msg}')logger.debug(f'Element xpath: {element_node.xpath}')diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.pyindex f2ccae2bc..06b9255aa 100644--- a/browser_use/dom/playground/tree.py+++ b/browser_use/dom/playground/tree.py@@ -3,91 +3,93 @@ import jsonimport timeimport aiofiles-import httpx-from playwright.async_api import async_playwright-from browser_use.browser import Browser-from browser_use.dom.serializer import DOMTreeSerializer-from browser_use.dom.service import DOMService+from browser_use.browser import BrowserSession+from browser_use.dom.service import DomServiceasync def main():- async with async_playwright() as p:- playwright_browser = await p.chromium.launch(args=['--remote-debugging-port=9222'], headless=False)- browser = Browser(browser=playwright_browser)+ # async with async_playwright() as p:+ # playwright_browser = await p.chromium.launch(args=['--remote-debugging-port=9222'], headless=False)+ browser = BrowserSession()- async with httpx.AsyncClient() as client:- version_info = await client.get('http://localhost:9222/json/version')- browser.cdp_url = version_info.json()['webSocketDebuggerUrl']+ # async with httpx.AsyncClient() as client:+ # version_info = await client.get('http://localhost:9222/json/version')+ # browser.cdp_url = version_info.json()['webSocketDebuggerUrl']- # await browser.create_new_tab('https://en.wikipedia.org/wiki/Apple_Inc.')- # await browser.create_new_tab('https://semantic-ui.com/modules/dropdown.html#/definition')- await browser.create_new_tab('https://select2.org/data-sources/ajax')- await browser._wait_for_page_and_frames_load()+ # if not browser.cdp_url:+ # raise ValueError('CDP URL is not set') # can't happen in this case actually- dom_service = DOMService(browser)+ # await browser.create_new_tab('https://en.wikipedia.org/wiki/Apple_Inc.')+ # await browser.create_new_tab('https://semantic-ui.com/modules/dropdown.html#/definition')+ await browser.create_new_tab('https://select2.org/data-sources/ajax')+ await browser._wait_for_page_and_frames_load()- while True:- start = time.time()- dom_tree = await dom_service.get_dom_tree()- end = time.time()- print(f'Time taken: {end - start} seconds')+ page = await browser.get_current_page()- async with aiofiles.open('tmp/enhanced_dom_tree.json', 'w') as f:- await f.write(json.dumps(dom_tree.__json__(), indent=1))+ dom_service = DomService(browser, page)- print('Saved enhanced dom tree to tmp/enhanced_dom_tree.json')+ while True:+ start = time.time()+ dom_tree = await dom_service.get_dom_tree()+ end = time.time()+ print(f'Time taken: {end - start} seconds')- # Print some sample information about visible/clickable elements- visible_clickable_count = 0- total_with_snapshot = 0+ async with aiofiles.open('tmp/enhanced_dom_tree.json', 'w') as f:+ await f.write(json.dumps(dom_tree.__json__(), indent=1))- def count_elements(node):- nonlocal visible_clickable_count, total_with_snapshot- if node.snapshot_node:- total_with_snapshot += 1- if node.snapshot_node.is_visible and node.snapshot_node.is_clickable:- visible_clickable_count += 1- # print(f'Visible clickable element: {node.node_name} (cursor: {node.snapshot_node.cursor_style})')+ print('Saved enhanced dom tree to tmp/enhanced_dom_tree.json')- if node.children_nodes:- for child in node.children_nodes:- count_elements(child)+ # Print some sample information about visible/clickable elements+ visible_clickable_count = 0+ total_with_snapshot = 0- count_elements(dom_tree)- print(- f'Found {visible_clickable_count} visible clickable elements out of {total_with_snapshot} elements with snapshot data'- )+ def count_elements(node):+ nonlocal visible_clickable_count, total_with_snapshot+ if node.snapshot_node:+ total_with_snapshot += 1+ if node.snapshot_node.is_visible and node.snapshot_node.is_clickable:+ visible_clickable_count += 1+ # print(f'Visible clickable element: {node.node_name} (cursor: {node.snapshot_node.cursor_style})')- serialized, selector_map = DOMTreeSerializer(dom_tree).serialize_accessible_elements()+ if node.children_nodes:+ for child in node.children_nodes:+ count_elements(child)- async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:- await f.write(serialized)+ count_elements(dom_tree)+ print(+ f'Found {visible_clickable_count} visible clickable elements out of {total_with_snapshot} elements with snapshot data'+ )- # print(serialized)- print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')+ serialized_dom_state = await dom_service.get_serialized_dom_tree()- # print(selector_map)+ async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:+ await f.write(serialized_dom_state.llm_representation())- # start = time.time()- # snapshot, dom_tree, ax_tree = await dom_service._get_all_trees()- # end = time.time()- # print(f'Time taken: {end - start} seconds')+ # print(serialized)+ print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')- # async with aiofiles.open('tmp/snapshot.json', 'w') as f:- # await f.write(json.dumps(snapshot, indent=1))+ # print(selector_map)- # async with aiofiles.open('tmp/dom_tree.json', 'w') as f:- # await f.write(json.dumps(dom_tree, indent=1))+ # start = time.time()+ # snapshot, dom_tree, ax_tree = await dom_service._get_all_trees()+ # end = time.time()+ # print(f'Time taken: {end - start} seconds')- # async with aiofiles.open('tmp/ax_tree.json', 'w') as f:- # await f.write(json.dumps(ax_tree, indent=1))+ # async with aiofiles.open('tmp/snapshot.json', 'w') as f:+ # await f.write(json.dumps(snapshot, indent=1))- # print('saved dom tree to tmp/dom_tree.json')- # print('saved snapshot to tmp/snapshot.json')- # print('saved ax tree to tmp/ax_tree.json')+ # async with aiofiles.open('tmp/dom_tree.json', 'w') as f:+ # await f.write(json.dumps(dom_tree, indent=1))- input('Done. Press Enter to continue...')+ # async with aiofiles.open('tmp/ax_tree.json', 'w') as f:+ # await f.write(json.dumps(ax_tree, indent=1))++ # print('saved dom tree to tmp/dom_tree.json')+ # print('saved snapshot to tmp/snapshot.json')+ # print('saved ax tree to tmp/ax_tree.json')++ input('Done. Press Enter to continue...')if __name__ == '__main__':diff --git a/browser_use/dom/serializer.py b/browser_use/dom/serializer.pyindex 54124b277..b367b4051 100644--- a/browser_use/dom/serializer.py+++ b/browser_use/dom/serializer.py@@ -1,74 +1,31 @@# @file purpose: Serializes enhanced DOM trees to string format for LLM consumption-from dataclasses import dataclass, fieldfrom cdp_use.cdp.accessibility.types import AXPropertyName-from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType--DEFAULT_INCLUDE_ATTRIBUTES = [- 'title',- 'type',- 'checked',- 'name',- 'role',- 'value',- 'placeholder',- 'data-date-format',- 'alt',- 'aria-label',- 'aria-expanded',- 'data-state',- 'aria-checked',-]---@dataclass(slots=True)-class SimplifiedNode:- """Simplified tree node for optimization."""-- original_node: EnhancedDOMTreeNode- children: list['SimplifiedNode'] = field(default_factory=list)- should_display: bool = True- interactive_index: int | None = None-- def is_clickable(self) -> bool:- """Check if this node is clickable/interactive."""- if self.original_node.snapshot_node:- return self.original_node.snapshot_node.is_clickable or False- return False-- def count_direct_clickable_children(self) -> int:- """Count how many direct children are clickable."""- return sum(1 for child in self.children if child.is_clickable())-- def has_any_clickable_descendant(self) -> bool:- """Check if this node or any descendant is clickable."""- if self.is_clickable():- return True- return any(child.has_any_clickable_descendant() for child in self.children)+from browser_use.dom.utils import cap_text_length+from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType, SerializedDOMState, SimplifiedNodeclass DOMTreeSerializer:"""Serializes enhanced DOM trees to string format."""- def __init__(self, root_node: EnhancedDOMTreeNode):+ def __init__(self, root_node: EnhancedDOMTreeNode, previous_cached_state: SerializedDOMState | None = None):self.root_node = root_nodeself._interactive_counter = 1self._selector_map: DOMSelectorMap = {}- def serialize_accessible_elements(self, include_attributes: list[str] | None = None) -> tuple[str, DOMSelectorMap]:+ self._previous_cached_selector_map = previous_cached_state.selector_map if previous_cached_state else None++ def serialize_accessible_elements(self) -> SerializedDOMState:"""Convert the enhanced DOM tree to string format, showing accessible elements and text content.- include_attributes: list[str] = include_attributes or `DEFAULT_INCLUDE_ATTRIBUTES`Returns:- Serialized string representation- Selector map mapping interactive indices to DOM nodes"""- if not include_attributes:- include_attributes = DEFAULT_INCLUDE_ATTRIBUTES# Reset stateself._interactive_counter = 1@@ -81,12 +38,9 @@ class DOMTreeSerializer:optimized_tree = self._optimize_tree(simplified_tree)# Step 3: Assign interactive indices to clickable elements- self._assign_interactive_indices(optimized_tree)-- # Step 4: Serialize optimized tree- serialized = self._serialize_tree(optimized_tree, include_attributes)+ self._assign_interactive_indices_and_mark_new_nodes(optimized_tree)- return serialized, self._selector_map+ return SerializedDOMState(_root=optimized_tree, selector_map=self._selector_map)def _create_simplified_tree(self, node: EnhancedDOMTreeNode) -> SimplifiedNode | None:"""Step 1: Create a simplified tree with relevant elements."""@@ -185,7 +139,7 @@ class DOMTreeSerializer:# Remove empty nodesreturn None- def _assign_interactive_indices(self, node: SimplifiedNode | None) -> None:+ def _assign_interactive_indices_and_mark_new_nodes(self, node: SimplifiedNode | None) -> None:"""Assign interactive indices to clickable elements."""if not node:return@@ -196,12 +150,23 @@ class DOMTreeSerializer:self._selector_map[self._interactive_counter] = node.original_nodeself._interactive_counter += 1+ # If we provided previous cached selector map, check if the node is new+ # TODO: maybe we can also check for more than just 1 step+ previous_backend_node_ids: set[int] | None = set()+ if self._previous_cached_selector_map:+ previous_backend_node_ids = {node.backend_node_id for node in self._previous_cached_selector_map.values()}++ if previous_backend_node_ids:+ if node.original_node.backend_node_id in previous_backend_node_ids:+ node.is_new = True+# Process childrenfor child in node.children:- self._assign_interactive_indices(child)+ self._assign_interactive_indices_and_mark_new_nodes(child)- def _serialize_tree(self, node: SimplifiedNode | None, include_attributes: list[str], depth: int = 0) -> str:- """Step 3: Serialize the optimized tree to string format."""+ @staticmethod+ def serialize_tree(node: SimplifiedNode | None, include_attributes: list[str], depth: int = 0) -> str:+ """Serialize the optimized tree to string format."""if not node:return ''@@ -213,7 +178,7 @@ class DOMTreeSerializer:# Skip displaying nodes marked as should_display=False (virtual nodes)if not node.should_display:for child in node.children:- child_text = self._serialize_tree(child, include_attributes, depth)+ child_text = DOMTreeSerializer.serialize_tree(child, include_attributes, depth)if child_text:formatted_text.append(child_text)return '\n'.join(formatted_text)@@ -223,7 +188,7 @@ class DOMTreeSerializer:next_depth += 1# Build attributes string- attributes_html_str = self._build_attributes_string(node.original_node, include_attributes, '')+ attributes_html_str = DOMTreeSerializer._build_attributes_string(node.original_node, include_attributes, '')# Build the lineif node.original_node.is_scrollable and node.interactive_index is None:@@ -231,8 +196,9 @@ class DOMTreeSerializer:line = f'{depth_str}|SCROLL|<{node.original_node.node_name}'elif node.interactive_index is not None:# Clickable (and possibly scrollable)+ new_prefix = '*' if node.is_new else ''scroll_prefix = '|SCROLL+' if node.original_node.is_scrollable else '['- line = f'{depth_str}{scroll_prefix}{node.interactive_index}]<{node.original_node.node_name}'+ line = f'{depth_str}{scroll_prefix}{new_prefix}{node.interactive_index}]<{node.original_node.node_name}'else:line = f'{depth_str}<{node.original_node.node_name}'@@ -256,13 +222,14 @@ class DOMTreeSerializer:# Process childrenfor child in node.children:- child_text = self._serialize_tree(child, include_attributes, next_depth)+ child_text = DOMTreeSerializer.serialize_tree(child, include_attributes, next_depth)if child_text:formatted_text.append(child_text)return '\n'.join(formatted_text)- def _build_attributes_string(self, node: EnhancedDOMTreeNode, include_attributes: list[str], text: str) -> str:+ @staticmethod+ def _build_attributes_string(node: EnhancedDOMTreeNode, include_attributes: list[str], text: str) -> str:"""Build the attributes string for an element."""if not node.attributes:return ''@@ -292,7 +259,7 @@ class DOMTreeSerializer:del attributes_to_include[key]# Remove attributes that duplicate accessibility data- role = self._get_accessibility_role(node)+ role = DOMTreeSerializer._get_accessibility_role(node)if role and node.node_name == role:attributes_to_include.pop('role', None)@@ -302,18 +269,13 @@ class DOMTreeSerializer:del attributes_to_include[attr]if attributes_to_include:- return ' '.join(f'{key}={self._cap_text_length(value, 15)}' for key, value in attributes_to_include.items())+ return ' '.join(f'{key}={cap_text_length(value, 15)}' for key, value in attributes_to_include.items())return ''- def _get_accessibility_role(self, node: EnhancedDOMTreeNode) -> str | None:+ @staticmethod+ def _get_accessibility_role(node: EnhancedDOMTreeNode) -> str | None:"""Get the accessibility role from the AX node."""if node.ax_node:return node.ax_node.rolereturn None-- def _cap_text_length(self, text: str, max_length: int) -> str:- """Cap text length for display."""- if len(text) <= max_length:- return text- return text[:max_length] + '...'diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex c8e6a7cdd..32519b5b4 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -1,6 +1,8 @@import asyncioimport time+from typing import TYPE_CHECKING+import httpxfrom cdp_use import CDPClientfrom cdp_use.cdp.accessibility.commands import GetFullAXTreeReturnsfrom cdp_use.cdp.accessibility.types import AXNode, AXPropertyName@@ -8,33 +10,69 @@ from cdp_use.cdp.dom.commands import GetDocumentReturnsfrom cdp_use.cdp.dom.types import Node, ShadowRootTypefrom cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns-from browser_use.browser import Browserfrom browser_use.dom.enhanced_snapshot import (REQUIRED_COMPUTED_STYLES,build_snapshot_lookup,)from browser_use.dom.serializer import DOMTreeSerializer-from browser_use.dom.views import EnhancedAXNode, EnhancedAXProperty, EnhancedDOMTreeNode, NodeType+from browser_use.dom.views import (+ EnhancedAXNode,+ EnhancedAXProperty,+ EnhancedDOMTreeNode,+ NodeType,+ SerializedDOMState,+)++if TYPE_CHECKING:+ from browser_use.browser.session import BrowserSession+ from browser_use.browser.types import Page+++class DomService:+ """+ Service for getting the DOM tree and other DOM-related information.+ Either browser or page must be provided.-class DOMService:- def __init__(self, browser: Browser):+ TODO: currently we start a new websocket connection PER STEP, we should definitely keep this persistent+ """++ def __init__(self, browser: 'BrowserSession', page: 'Page'):self.browser = browser+ self.page = pageself.cdp_client: CDPClient | None = Noneself.playwright_page_to_session_id_store: dict[str, str] = {}async def _get_cdp_client(self) -> CDPClient:- if self.cdp_client is None:- if not self.browser.cdp_url:- raise ValueError('CDP URL is not set')+ if not self.browser.cdp_url:+ raise ValueError('CDP URL is not set')++ # TODO: MOVE THIS TO BROWSER SESSION (or sth idk)+ # If the cdp_url is already a websocket URL, use it as-is.+ if self.browser.cdp_url.startswith('ws'):+ ws_url = self.browser.cdp_url+ else:+ # Otherwise, treat it as the DevTools HTTP root and fetch the websocket URL.+ url = self.browser.cdp_url.rstrip('/')+ if not url.endswith('/json/version'):+ url = url + '/json/version'+ async with httpx.AsyncClient() as client:+ version_info = await client.get(url)+ ws_url = version_info.json()['webSocketDebuggerUrl']- self.cdp_client = CDPClient(self.browser.cdp_url)+ if self.cdp_client is None:+ self.cdp_client = CDPClient(ws_url)await self.cdp_client.start()+return self.cdp_client+ async def __aenter__(self):+ await self._get_cdp_client()+ return self+# on self destroy -> stop the cdp client- async def __del__(self):+ async def __aexit__(self, exc_type, exc_value, traceback):if self.cdp_client:await self.cdp_client.stop()self.cdp_client = None@@ -44,8 +82,7 @@ class DOMService:TODO: this is a REALLY hacky way -> if multiple same urls are open then this will break"""- page = await self.browser.get_current_page()- page_guid = page._impl_obj._guid+ page_guid = self.page._impl_obj._guid# if page_guid in self.page_to_session_id_store:# return self.page_to_session_id_store[page_guid]@@ -54,7 +91,7 @@ class DOMService:targets = await cdp_client.send.Target.getTargets()for target in targets['targetInfos']:- if target['type'] == 'page' and target['url'] == page.url:+ if target['type'] == 'page' and target['url'] == self.page.url:# cache the session id for this playwright pageself.playwright_page_to_session_id_store[page_guid] = target['targetId']@@ -72,7 +109,7 @@ class DOMService:return session_id- raise ValueError(f'No session id found for page {page.url}')+ raise ValueError(f'No session id found for page {self.page.url}')def _build_enhanced_ax_node(self, ax_node: AXNode) -> EnhancedAXNode:properties: list[EnhancedAXProperty] | None = None@@ -167,7 +204,7 @@ class DOMService:node_type=NodeType(node['nodeType']),node_name=node['nodeName'],node_value=node['nodeValue'],- attributes=attributes,+ attributes=attributes or {},is_scrollable=node.get('isScrollable', None),frame_id=node.get('frameId', None),content_document=None,@@ -244,20 +281,17 @@ class DOMService:return enhanced_dom_tree- async def get_serialized_dom_tree(- self, include_attributes: list[str] | None = None- ) -> tuple[str, dict[int, EnhancedDOMTreeNode]]:+ async def get_serialized_dom_tree(self, previous_cached_state: SerializedDOMState | None = None) -> SerializedDOMState:"""Get the serialized DOM tree representation for LLM consumption.- Returns:- - Serialized string representation- - Selector map mapping interactive indices to DOM nodes+ TODO: this is a bit of a hack, we should probably have a better way to do this"""enhanced_dom_tree = await self.get_dom_tree()start = time.time()- serialized, selector_map = DOMTreeSerializer(enhanced_dom_tree).serialize_accessible_elements(include_attributes)+ serialized_dom_state = DOMTreeSerializer(enhanced_dom_tree, previous_cached_state).serialize_accessible_elements()+end = time.time()print(f'Time taken to serialize dom tree: {end - start} seconds')- return serialized, selector_map+ return serialized_dom_statediff --git a/browser_use/dom/utils.py b/browser_use/dom/utils.pynew file mode 100644index 000000000..ce45ec732--- /dev/null+++ b/browser_use/dom/utils.py@@ -0,0 +1,5 @@+def cap_text_length(text: str, max_length: int) -> str:+ """Cap text length for display."""+ if len(text) <= max_length:+ return text+ return text[:max_length] + '...'diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 61a5ec82f..64d3fb903 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -1,10 +1,61 @@-from dataclasses import asdict, dataclass+import hashlib+from dataclasses import asdict, dataclass, fieldfrom enum import Enumfrom typing import Anyfrom cdp_use.cdp.accessibility.types import AXPropertyNamefrom cdp_use.cdp.dom.types import ShadowRootType+from browser_use.dom.utils import cap_text_length++### Serializer types+DEFAULT_INCLUDE_ATTRIBUTES = [+ 'title',+ 'type',+ 'checked',+ 'name',+ 'role',+ 'value',+ 'placeholder',+ 'data-date-format',+ 'alt',+ 'aria-label',+ 'aria-expanded',+ 'data-state',+ 'aria-checked',+]+++@dataclass(slots=True)+class SimplifiedNode:+ """Simplified tree node for optimization."""++ original_node: 'EnhancedDOMTreeNode'+ children: list['SimplifiedNode'] = field(default_factory=list)+ should_display: bool = True+ interactive_index: int | None = None++ is_new: bool = False++ def is_clickable(self) -> bool:+ """Check if this node is clickable/interactive."""+ if self.original_node.snapshot_node:+ return self.original_node.snapshot_node.is_clickable or False+ return False++ def count_direct_clickable_children(self) -> int:+ """Count how many direct children are clickable."""+ return sum(1 for child in self.children if child.is_clickable())++ def has_any_clickable_descendant(self) -> bool:+ """Check if this node or any descendant is clickable."""+ if self.is_clickable():+ return True+ return any(child.has_any_clickable_descendant() for child in self.children)+++###+class NodeType(int, Enum):"""DOM node types based on the DOM specification."""@@ -23,12 +74,6 @@ class NodeType(int, Enum):NOTATION_NODE = 12-# @dataclass-# class EnchancedAXRelatedNode:-# node: 'EnhancedDOMTreeNode'-# text: str | None--@dataclass(slots=True)class EnhancedAXProperty:"""we don't need `sources` and `related_nodes` for now (not sure how to use them)@@ -38,7 +83,7 @@ class EnhancedAXProperty:name: AXPropertyNamevalue: str | bool | None- # related_nodes: list[EnchancedAXRelatedNode] | None+ # related_nodes: list[EnhancedAXRelatedNode] | None@dataclass(slots=True)@@ -54,6 +99,12 @@ class EnhancedAXNode:properties: list[EnhancedAXProperty] | None+@dataclass+class DOMCoordinates:+ x: float+ y: float++@dataclass(slots=True)class DOMRect:x: float@@ -61,6 +112,10 @@ class DOMRect:width: floatheight: float+ @property+ def center(self) -> DOMCoordinates:+ return DOMCoordinates(x=self.x + self.width / 2, y=self.y + self.height / 2)+@dataclass(slots=True)class EnhancedSnapshotNode:@@ -94,7 +149,7 @@ class EnhancedSnapshotNode:@dataclass(slots=True)class EnhancedDOMTreeNode:"""- Enchanced DOM tree node that contains information from AX, DOM, and Snapshot trees. It's mostly based on the types on DOM node type with enchanced data from AX and Snapshot trees.+ Enhanced DOM tree node that contains information from AX, DOM, and Snapshot trees. It's mostly based on the types on DOM node type with enhanced data from AX and Snapshot trees.@dev when serializing check if the value is a valid value first!@@ -114,7 +169,7 @@ class EnhancedDOMTreeNode:"""Only applicable for `NodeType.ELEMENT_NODE`"""node_value: str"""this is where the value from `NodeType.TEXT_NODE` is stored usually"""- attributes: dict[str, str] | None+ attributes: dict[str, str]"""slightly changed from the original attributes to be more readable"""is_scrollable: bool | None"""@@ -151,7 +206,19 @@ class EnhancedDOMTreeNode:# endregion - Snapshot Node data@property- def x_path(self) -> str:+ def parent(self) -> 'EnhancedDOMTreeNode | None':+ return self.parent_node++ @property+ def children(self) -> list['EnhancedDOMTreeNode']:+ return self.children_nodes or []++ @property+ def tag_name(self) -> str:+ return self.node_name.lower()++ @property+ def xpath(self) -> str:"""Generate XPath for this DOM node, stopping at shadow boundaries or iframes."""segments = []current_element = self@@ -215,24 +282,135 @@ class EnhancedDOMTreeNode:'children_nodes': [c.__json__() for c in self.children_nodes] if self.children_nodes else [],}+ def get_all_children_text(self, max_depth: int = -1) -> str:+ text_parts = []++ def collect_text(node: EnhancedDOMTreeNode, current_depth: int) -> None:+ if max_depth != -1 and current_depth > max_depth:+ return++ # Skip this branch if we hit a highlighted element (except for the current node)+ # TODO: think whether if makese sense to add text until the next clickable element or everything from children+ # if node.node_type == NodeType.ELEMENT_NODE+ # if isinstance(node, DOMElementNode) and node != self and node.highlight_index is not None:+ # return++ if node.node_type == NodeType.TEXT_NODE:+ text_parts.append(node.node_value)+ elif node.node_type == NodeType.ELEMENT_NODE:+ for child in node.children:+ collect_text(child, current_depth + 1)++ collect_text(self, 0)+ return '\n'.join(text_parts).strip()++ def __repr__(self) -> str:+ """+ @DEV ! don't display this to the LLM, it's SUPER long+ """+ attributes = ', '.join([f'{k}={v}' for k, v in self.attributes.items()])+ is_scrollable = getattr(self, 'is_scrollable', False)+ num_children = len(self.children_nodes or [])+ return (+ f'<{self.tag_name} {attributes} is_scrollable={is_scrollable} '+ f'num_children={num_children} >{self.node_value}</{self.tag_name}>'+ )++ def llm_representation(self, max_text_length: int = 25) -> str:+ """+ Token friendly representation of the node, used in the LLM+ """++ return f'<{self.tag_name}>{cap_text_length(self.get_all_children_text(), max_text_length) or ""}'++ @property+ def element_hash(self) -> int:+ return hash(self)++ def __hash__(self) -> int:+ """+ Hash the element based on its parent branch path and attributes.++ TODO: migrate this to use only backendNodeId + current SessionId+ """++ # Get parent branch path+ parent_branch_path = self._get_parent_branch_path()+ parent_branch_path_string = '/'.join(parent_branch_path)++ # Get attributes hash+ attributes_string = ''.join(f'{key}={value}' for key, value in self.attributes.items())++ # Combine both for final hash+ combined_string = f'{parent_branch_path_string}|{attributes_string}'+ element_hash = hashlib.sha256(combined_string.encode()).hexdigest()++ # Convert to int for __hash__ return type - use first 16 chars and convert from hex to int+ return int(element_hash[:16], 16)++ def _get_parent_branch_path(self) -> list[str]:+ """Get the parent branch path as a list of tag names from root to current element."""+ parents: list['EnhancedDOMTreeNode'] = []+ current_element: 'EnhancedDOMTreeNode | None' = self++ while current_element is not None:+ if current_element.node_type == NodeType.ELEMENT_NODE:+ parents.append(current_element)+ current_element = current_element.parent_node++ parents.reverse()+ return [parent.tag_name for parent in parents]+DOMSelectorMap = dict[int, EnhancedDOMTreeNode]@dataclass-class DOMState: #- root: EnhancedDOMTreeNode+class SerializedDOMState:+ _root: SimplifiedNode | None+ """Not meant to be used directly, use `llm_representation` instead"""++ selector_map: DOMSelectorMap++ def llm_representation(+ self,+ include_attributes: list[str] | None = None,+ ) -> str:+ """Kinda ugly, but leaving this as an internal method because include_attributes are a parameter on the agent, so we need to leave it as a 2 step process"""+ from browser_use.dom.serializer import DOMTreeSerializer++ if not self._root:+ return 'Empty DOM tree'++ include_attributes = include_attributes or DEFAULT_INCLUDE_ATTRIBUTES++ return DOMTreeSerializer.serialize_tree(self._root, include_attributes)@dataclassclass DOMInteractedElement:+ """+ DOMInteractedElement is a class that represents a DOM element that has been interacted with.+ It is used to store the DOM element that has been interacted with and to store the DOM element that has been interacted with.++ TODO: this is a bit of a hack, we should probably have a better way to do this+ """++ node_id: int+ backend_node_id: int+ frame_id: str | None+node_type: NodeTypenode_value: strnode_name: strattributes: dict[str, str] | None+ bounds: DOMRect | None+x_path: str+ element_hash: int+def to_dict(self) -> dict[str, Any]:return {'node_type': self.node_type.value,@@ -241,3 +419,18 @@ class DOMInteractedElement:'attributes': self.attributes,'x_path': self.x_path,}++ @classmethod+ def load_from_enhanced_dom_tree(cls, enhanced_dom_tree: EnhancedDOMTreeNode) -> 'DOMInteractedElement':+ return cls(+ node_id=enhanced_dom_tree.node_id,+ backend_node_id=enhanced_dom_tree.backend_node_id,+ frame_id=enhanced_dom_tree.frame_id,+ node_type=enhanced_dom_tree.node_type,+ node_value=enhanced_dom_tree.node_value,+ node_name=enhanced_dom_tree.node_name,+ attributes=enhanced_dom_tree.attributes,+ bounds=enhanced_dom_tree.snapshot_node.bounds if enhanced_dom_tree.snapshot_node else None,+ x_path=enhanced_dom_tree.xpath,+ element_hash=hash(enhanced_dom_tree),+ )diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.pyindex b990804b6..7315423e8 100644--- a/browser_use/llm/tests/test_single_step.py+++ b/browser_use/llm/tests/test_single_step.py@@ -6,7 +6,7 @@ import pytestfrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.agent.service import Agentfrom browser_use.browser.views import BrowserStateSummary, TabInfo-from browser_use.dom.views import DOMElementNode, SelectorMap+from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType, SerializedDOMState, SimplifiedNodefrom browser_use.filesystem.file_system import FileSystemfrom browser_use.llm.anthropic.chat import ChatAnthropicfrom browser_use.llm.azure.chat import ChatAzureOpenAI@@ -24,25 +24,26 @@ def create_mock_state_message(temp_dir: str):"""Create a mock state message with a single clickable element."""# Create a mock DOM element with a single clickable button- mock_button = DOMElementNode(- tag_name='button',- xpath="//button[@id='test-button']",+ mock_button = EnhancedDOMTreeNode(+ node_id=1,+ backend_node_id=1,+ node_type=NodeType.ELEMENT_NODE,+ node_name='button',+ node_value='Click Me',attributes={'id': 'test-button'},- children=[],- is_visible=True,- is_interactive=True,- is_top_element=True,- is_in_viewport=True,- shadow_root=False,- highlight_index=1, # This makes it clickable with index 1- viewport_coordinates=None,- page_coordinates=None,- viewport_info=None,- parent=None,+ is_scrollable=False,+ frame_id=None,+ content_document=None,+ shadow_root_type=None,+ shadow_roots=None,+ parent_node=None,+ children_nodes=None,+ ax_node=None,+ snapshot_node=None,)# Create selector map- selector_map: SelectorMap = {1: mock_button}+ selector_map: DOMSelectorMap = {1: mock_button}# Create mock tab info with proper integer page_idmock_tab = TabInfo(@@ -51,10 +52,19 @@ def create_mock_state_message(temp_dir: str):title='Test Page',)+ dom_state = SerializedDOMState(+ _root=SimplifiedNode(+ original_node=mock_button,+ children=[],+ should_display=True,+ interactive_index=1,+ ),+ selector_map=selector_map,+ )+# Create mock browser state with required selector_mapmock_browser_state = BrowserStateSummary(- element_tree=mock_button, # Using the actual DOM element- selector_map=selector_map, # Added missing parameter+ dom_state=dom_state, # Using the actual DOM elementurl='https://example.com',title='Test Page',tabs=[mock_tab],@@ -81,7 +91,7 @@ def create_mock_state_message(temp_dir: str):)# Override the clickable_elements_to_string method to return our simple element- mock_button.clickable_elements_to_string = lambda include_attributes=None: '[1]<button id="test-button">Click Me</button>'+ dom_state.llm_representation = lambda include_attributes=None: '[1]<button id="test-button">Click Me</button>'# Get the formatted messagemessage = agent_prompt.get_user_message(use_vision=False)diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.pyindex 0e8ca777a..59b146e9c 100644--- a/browser_use/mcp/server.py+++ b/browser_use/mcp/server.py@@ -663,11 +663,11 @@ class BrowserUseServer:}# Add interactive elements with their indices- for index, element in state.selector_map.items():+ for index, element in state.dom_state.selector_map.items():elem_info = {'index': index,'tag': element.tag_name,- 'text': element.get_all_text_till_next_clickable_element(max_depth=2)[:100],+ 'text': element.get_all_children_text(max_depth=2)[:100],}if element.attributes.get('placeholder'):elem_info['placeholder'] = element.attributes['placeholder']diff --git a/examples/simple.py b/examples/simple.pyindex f9bfe8132..394549d9d 100644--- a/examples/simple.py+++ b/examples/simple.py@@ -19,7 +19,7 @@ llm = ChatOpenAI()-task = 'Find the founders of browser-use'+task = 'Go to google.com/travel/flights and find the cheapest flight from New York to Paris on 2025-07-15'agent = Agent(task=task, llm=llm)diff --git a/tests/ci/test_action_parameter_injection.py b/tests/ci/test_action_parameter_injection.pyindex b67a57a6c..98a0e97e3 100644--- a/tests/ci/test_action_parameter_injection.py+++ b/tests/ci/test_action_parameter_injection.py@@ -5,7 +5,7 @@ import pytestfrom pytest_httpserver import HTTPServerfrom browser_use.browser import BrowserProfile, BrowserSession-from browser_use.dom.views import DOMElementNode+from browser_use.dom.views import EnhancedDOMTreeNode, NodeTypeclass TestBrowserContext:@@ -132,13 +132,22 @@ class TestBrowserContext:it returns the correct CSS selector string for a DOMElementNode."""# Create a DOMElementNode instance with a complex set of attributes- dummy_element = DOMElementNode(- tag_name='div',- is_visible=True,- parent=None,- xpath='/html/body/div[2]',+ dummy_element = EnhancedDOMTreeNode(+ node_id=1,+ backend_node_id=1,+ node_type=NodeType.ELEMENT_NODE,+ node_name='div',+ node_value='',attributes={'class': 'foo bar', 'id': 'my-id', 'placeholder': 'some "quoted" text', 'data-testid': '123'},- children=[],+ is_scrollable=False,+ frame_id=None,+ content_document=None,+ shadow_root_type=None,+ shadow_roots=None,+ parent_node=None,+ children_nodes=None,+ ax_node=None,+ snapshot_node=None,)# Call the method with include_dynamic_attributes=Truediff --git a/tests/ci/test_browser_session_downloads.py b/tests/ci/test_browser_session_downloads.pyindex 38125cac8..ccb286896 100644--- a/tests/ci/test_browser_session_downloads.py+++ b/tests/ci/test_browser_session_downloads.py@@ -54,8 +54,8 @@ async def test_download_detection_timing(test_server, tmp_path):# Find the button elementbutton_node = None- for elem in state.selector_map.values():- if elem.tag_name == 'button' and elem.attributes.get('id') == 'test-button':+ for elem in state.dom_state.selector_map.values():+ if elem.node_name == 'button' and elem.attributes.get('id') == 'test-button':button_node = elembreak@@ -94,8 +94,8 @@ async def test_download_detection_timing(test_server, tmp_path):# Find the button element againbutton_node = None- for elem in state.selector_map.values():- if elem.tag_name == 'button' and elem.attributes.get('id') == 'test-button':+ for elem in state.dom_state.selector_map.values():+ if elem.node_name == 'button' and elem.attributes.get('id') == 'test-button':button_node = elembreak@@ -145,8 +145,8 @@ async def test_actual_download_detection(test_server, tmp_path):# Find the download link elementdownload_node = None- for elem in state.selector_map.values():- if elem.tag_name == 'a' and 'download' in elem.attributes:+ for elem in state.dom_state.selector_map.values():+ if elem.node_name == 'a' and 'download' in elem.attributes:download_node = elembreak