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
wip, added serializer
Gregor Žunič900fdb650126
diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.pyindex adc5a959a..fd1e2f60f 100644--- a/browser_use/dom/enhanced_snapshot.py+++ b/browser_use/dom/enhanced_snapshot.py@@ -17,10 +17,31 @@ from browser_use.dom.views import EnhancedSnapshotNode# Only the essential computed styles we actually needREQUIRED_COMPUTED_STYLES = [- 'display', # For visibility detection- 'visibility', # For visibility detection- 'opacity', # For visibility detection- 'cursor', # For cursor style extraction+ 'display',+ 'visibility',+ 'opacity',+ 'position',+ 'z-index',+ 'pointer-events',+ 'cursor',+ 'overflow',+ 'overflow-x',+ 'overflow-y',+ 'width',+ 'height',+ 'top',+ 'left',+ 'right',+ 'bottom',+ 'transform',+ 'clip',+ 'clip-path',+ 'user-select',+ 'background-color',+ 'color',+ 'border',+ 'margin',+ 'padding',]diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.pyindex 9a0a4b719..f2ccae2bc 100644--- a/browser_use/dom/playground/tree.py+++ b/browser_use/dom/playground/tree.py@@ -7,6 +7,7 @@ import httpxfrom playwright.async_api import async_playwrightfrom browser_use.browser import Browser+from browser_use.dom.serializer import DOMTreeSerializerfrom browser_use.dom.service import DOMService@@ -20,61 +21,73 @@ async def main():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://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()dom_service = DOMService(browser)- start = time.time()- dom_tree = await dom_service.get_dom_tree()- end = time.time()- print(f'Time taken: {end - start} seconds')+ while True:+ start = time.time()+ dom_tree = await dom_service.get_dom_tree()+ end = time.time()+ print(f'Time taken: {end - start} seconds')- async with aiofiles.open('tmp/enhanced_dom_tree.json', 'w') as f:- await f.write(json.dumps(dom_tree.__json__(), indent=1))+ async with aiofiles.open('tmp/enhanced_dom_tree.json', 'w') as f:+ await f.write(json.dumps(dom_tree.__json__(), indent=1))- print('Saved enhanced dom tree to tmp/enhanced_dom_tree.json')+ print('Saved enhanced dom tree to tmp/enhanced_dom_tree.json')- # Print some sample information about visible/clickable elements- visible_clickable_count = 0- total_with_snapshot = 0+ # Print some sample information about visible/clickable elements+ visible_clickable_count = 0+ total_with_snapshot = 0- 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})')+ 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})')- if node.children_nodes:- for child in node.children_nodes:- count_elements(child)+ if node.children_nodes:+ for child in node.children_nodes:+ count_elements(child)- count_elements(dom_tree)- print(- f'Found {visible_clickable_count} visible clickable elements out of {total_with_snapshot} elements with snapshot data'- )+ count_elements(dom_tree)+ print(+ f'Found {visible_clickable_count} visible clickable elements out of {total_with_snapshot} elements with snapshot data'+ )- # start = time.time()- # snapshot, dom_tree, ax_tree = await dom_service._get_all_trees()- # end = time.time()- # print(f'Time taken: {end - start} seconds')+ serialized, selector_map = DOMTreeSerializer(dom_tree).serialize_accessible_elements()- # async with aiofiles.open('tmp/snapshot.json', 'w') as f:- # await f.write(json.dumps(snapshot, indent=1))+ async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:+ await f.write(serialized)- # async with aiofiles.open('tmp/dom_tree.json', 'w') as f:- # await f.write(json.dumps(dom_tree, indent=1))+ # print(serialized)+ print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')- # async with aiofiles.open('tmp/ax_tree.json', 'w') as f:- # await f.write(json.dumps(ax_tree, indent=1))+ # print(selector_map)- # 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')+ # 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('Done')+ # async with aiofiles.open('tmp/snapshot.json', 'w') as f:+ # await f.write(json.dumps(snapshot, indent=1))++ # async with aiofiles.open('tmp/dom_tree.json', 'w') as f:+ # await f.write(json.dumps(dom_tree, indent=1))++ # 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 e69de29bb..e9b79a352 100644--- a/browser_use/dom/serializer.py+++ b/browser_use/dom/serializer.py@@ -0,0 +1,303 @@+# @file purpose: Serializes enhanced DOM trees to string format for LLM consumption++from dataclasses import dataclass, field++from cdp_use.cdp.accessibility.types import AXPropertyName++from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES, EnhancedDOMTreeNode, NodeType+++@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)+++class DOMTreeSerializer:+ """Serializes enhanced DOM trees to string format."""++ def __init__(self, root_node: EnhancedDOMTreeNode):+ self.root_node = root_node++ self._interactive_counter = 1+ self._selector_map: dict[int, EnhancedDOMTreeNode] = {}++ def serialize_accessible_elements(+ self, include_attributes: list[str] | None = None+ ) -> tuple[str, dict[int, EnhancedDOMTreeNode]]:+ """Convert the enhanced DOM tree to string format, showing accessible elements and text content.++ Returns:+ - Serialized string representation+ - Selector map mapping interactive indices to DOM nodes+ """+ if not include_attributes:+ include_attributes = DEFAULT_INCLUDE_ATTRIBUTES++ # Reset state+ self._interactive_counter = 1+ self._selector_map = {}++ # Step 1: Create simplified tree+ simplified_tree = self._create_simplified_tree(self.root_node)++ # Step 2: Optimize tree (remove unnecessary parents)+ 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)++ return serialized, self._selector_map++ def _create_simplified_tree(self, node: EnhancedDOMTreeNode) -> SimplifiedNode | None:+ """Step 1: Create a simplified tree with relevant elements."""++ if node.node_type == NodeType.DOCUMENT_NODE:+ # Document nodes - process children directly and return the first meaningful child+ if node.children_nodes:+ for child in node.children_nodes:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ return simplified_child+ return None++ elif node.node_type == NodeType.ELEMENT_NODE:+ # Skip #document nodes entirely - process children directly+ if node.node_name == '#document':+ if node.children_nodes:+ for child in node.children_nodes:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ return simplified_child+ return None++ # Skip elements that contain non-content+ if node.node_name.lower() in ['style', 'script', 'head', 'meta', 'link', 'title']:+ return None++ # Be more inclusive - include most elements and let optimization handle filtering+ # Include if: clickable, has AX data (non-ignored), or structural element, or has meaningful attributes++ has_focusable_property = (+ any(property.name == AXPropertyName.FOCUSABLE and property.value for property in node.ax_node.properties)+ if node.ax_node and node.ax_node.properties+ else False+ )++ cursor_pointer = node.snapshot_node and node.snapshot_node.cursor_style == 'pointer'++ is_clickable = node.snapshot_node and node.snapshot_node.is_clickable or has_focusable_property or cursor_pointer++ is_visible = node.snapshot_node and node.snapshot_node.is_visible+ is_scrollable = node.is_scrollable++ # Simple criteria: include if (clickable AND visible) OR scrollable+ should_include = (is_clickable and is_visible) or is_scrollable++ if should_include or node.children_nodes: # Include if meaningful OR has children to process+ simplified = SimplifiedNode(original_node=node)++ # Process children+ if node.children_nodes:+ for child in node.children_nodes:+ simplified_child = self._create_simplified_tree(child)+ if simplified_child:+ simplified.children.append(simplified_child)++ # Only return this node if it's meaningful OR has meaningful children+ if should_include or simplified.children:+ return simplified+ return None++ elif node.node_type == NodeType.TEXT_NODE:+ # Include text nodes only if visible+ is_visible = node.snapshot_node and node.snapshot_node.is_visible+ if is_visible and node.node_value and node.node_value.strip() and len(node.node_value.strip()) > 1:+ return SimplifiedNode(original_node=node)+ return None++ # Skip other node types (COMMENT_NODE, DOCUMENT_TYPE_NODE, etc.)+ return None++ def _optimize_tree(self, node: SimplifiedNode | None) -> SimplifiedNode | None:+ """Step 2: Simple optimization - just process children and keep meaningful nodes."""+ if not node:+ return None++ # Process all children+ optimized_children = []+ for child in node.children:+ optimized_child = self._optimize_tree(child)+ if optimized_child:+ optimized_children.append(optimized_child)++ # Update children with optimized versions+ node.children = optimized_children++ # Keep the node if it's meaningful or has meaningful children+ if (+ node.is_clickable()+ or node.original_node.is_scrollable+ or node.original_node.node_type == NodeType.TEXT_NODE+ or node.children+ ):+ return node++ # Remove empty nodes+ return None++ def _assign_interactive_indices(self, node: SimplifiedNode | None) -> None:+ """Assign interactive indices to clickable elements."""+ if not node:+ return++ # Assign index to clickable elements+ if node.is_clickable():+ node.interactive_index = self._interactive_counter+ self._selector_map[self._interactive_counter] = node.original_node+ self._interactive_counter += 1++ # Process children+ for child in node.children:+ self._assign_interactive_indices(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."""+ if not node:+ return ''++ formatted_text = []+ depth_str = depth * '\t'+ next_depth = depth++ if node.original_node.node_type == NodeType.ELEMENT_NODE:+ # 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)+ if child_text:+ formatted_text.append(child_text)+ return '\n'.join(formatted_text)++ # Add element with interactive_index if clickable or scrollable+ if node.interactive_index is not None or node.original_node.is_scrollable:+ next_depth += 1++ # Build attributes string+ attributes_html_str = self._build_attributes_string(node.original_node, include_attributes, '')++ # Build the line+ if node.original_node.is_scrollable and node.interactive_index is None:+ # Scrollable but not clickable+ line = f'{depth_str}|SCROLL|<{node.original_node.node_name}'+ elif node.interactive_index is not None:+ # Clickable (and possibly scrollable)+ scroll_prefix = '|SCROLL+' if node.original_node.is_scrollable else '['+ line = f'{depth_str}{scroll_prefix}{node.interactive_index}]<{node.original_node.node_name}'+ else:+ line = f'{depth_str}<{node.original_node.node_name}'++ if attributes_html_str:+ line += f' {attributes_html_str}'++ line += ' />'+ formatted_text.append(line)++ elif node.original_node.node_type == NodeType.TEXT_NODE:+ # Include all visible text where it naturally appears+ is_visible = node.original_node.snapshot_node and node.original_node.snapshot_node.is_visible+ if (+ is_visible+ and node.original_node.node_value+ and node.original_node.node_value.strip()+ and len(node.original_node.node_value.strip()) > 1+ ):+ clean_text = node.original_node.node_value.strip()+ formatted_text.append(f'{depth_str}{clean_text}')++ # Process children+ for child in node.children:+ child_text = self._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:+ """Build the attributes string for an element."""+ if not node.attributes:+ return ''++ attributes_to_include = {+ key: str(value).strip()+ for key, value in node.attributes.items()+ if key in include_attributes and str(value).strip() != ''+ }++ # Remove duplicate values+ ordered_keys = [key for key in include_attributes if key in attributes_to_include]++ if len(ordered_keys) > 1:+ keys_to_remove = set()+ seen_values = {}++ for key in ordered_keys:+ value = attributes_to_include[key]+ if len(value) > 5:+ if value in seen_values:+ keys_to_remove.add(key)+ else:+ seen_values[value] = key++ for key in keys_to_remove:+ del attributes_to_include[key]++ # Remove attributes that duplicate accessibility data+ role = self._get_accessibility_role(node)+ if role and node.node_name == role:+ attributes_to_include.pop('role', None)++ attrs_to_remove_if_text_matches = ['aria-label', 'placeholder', 'title']+ for attr in attrs_to_remove_if_text_matches:+ if attributes_to_include.get(attr) and attributes_to_include.get(attr, '').strip().lower() == text.strip().lower():+ 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 ''++ def _get_accessibility_role(self, node: EnhancedDOMTreeNode) -> str | None:+ """Get the accessibility role from the AX node."""+ if node.ax_node:+ return node.ax_node.role+ return 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 c450c10b6..c8e6a7cdd 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -13,6 +13,7 @@ from browser_use.dom.enhanced_snapshot import (REQUIRED_COMPUTED_STYLES,build_snapshot_lookup,)+from browser_use.dom.serializer import DOMTreeSerializerfrom browser_use.dom.views import EnhancedAXNode, EnhancedAXProperty, EnhancedDOMTreeNode, NodeType@@ -242,3 +243,21 @@ class DOMService:print(f'Time taken to build enhanced dom tree: {end - start} seconds')return enhanced_dom_tree++ async def get_serialized_dom_tree(+ self, include_attributes: list[str] | None = None+ ) -> tuple[str, dict[int, EnhancedDOMTreeNode]]:+ """Get the serialized DOM tree representation for LLM consumption.++ Returns:+ - Serialized string representation+ - Selector map mapping interactive indices to DOM nodes+ """+ enhanced_dom_tree = await self.get_dom_tree()++ start = time.time()+ serialized, selector_map = DOMTreeSerializer(enhanced_dom_tree).serialize_accessible_elements(include_attributes)+ end = time.time()+ print(f'Time taken to serialize dom tree: {end - start} seconds')++ return serialized, selector_mapdiff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 6881e11d1..b8ef942bf 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -151,6 +151,51 @@ class EnhancedDOMTreeNode:# endregion - Snapshot Node data+ @property+ def x_path(self) -> str:+ """Generate XPath for this DOM node, stopping at shadow boundaries or iframes."""+ segments = []+ current_element = self++ while current_element and current_element.node_type == NodeType.ELEMENT_NODE:+ # Stop if we hit a shadow root or iframe+ if current_element.parent_node and (+ current_element.parent_node.shadow_root_type is not None+ or current_element.parent_node.node_name.lower() == 'iframe'+ ):+ break++ position = self._get_element_position(current_element)+ tag_name = current_element.node_name.lower()+ xpath_index = f'[{position}]' if position > 0 else ''+ segments.insert(0, f'{tag_name}{xpath_index}')++ current_element = current_element.parent_node++ return '/'.join(segments)++ def _get_element_position(self, element: 'EnhancedDOMTreeNode') -> int:+ """Get the position of an element among its siblings with the same tag name.+ Returns 0 if it's the only element of its type, otherwise returns 1-based index."""+ if not element.parent_node or not element.parent_node.children_nodes:+ return 0++ same_tag_siblings = [+ child+ for child in element.parent_node.children_nodes+ if child.node_type == NodeType.ELEMENT_NODE and child.node_name.lower() == element.node_name.lower()+ ]++ if len(same_tag_siblings) <= 1:+ return 0 # No index needed if it's the only one++ try:+ # XPath is 1-indexed+ position = same_tag_siblings.index(element) + 1+ return position+ except ValueError:+ return 0+def __json__(self) -> dict:"""Serializes the node and its descendants to a dictionary, omitting parent references."""return {