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
added snapshot information
Gregor Žuničb867019244c6
diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.pynew file mode 100644index 000000000..adc5a959a--- /dev/null+++ b/browser_use/dom/enhanced_snapshot.py@@ -0,0 +1,133 @@+"""+Enhanced snapshot processing for browser-use DOM tree extraction.++This module provides stateless functions for parsing Chrome DevTools Protocol (CDP) DOMSnapshot data+to extract visibility, clickability, cursor styles, and other layout information.+"""++from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns+from cdp_use.cdp.domsnapshot.types import (+ DocumentSnapshot,+ LayoutTreeSnapshot,+ NodeTreeSnapshot,+ RareBooleanData,+)++from browser_use.dom.views import EnhancedSnapshotNode++# Only the essential computed styles we actually need+REQUIRED_COMPUTED_STYLES = [+ 'display', # For visibility detection+ 'visibility', # For visibility detection+ 'opacity', # For visibility detection+ 'cursor', # For cursor style extraction+]+++def _parse_rare_boolean_data(rare_data: RareBooleanData, index: int) -> bool | None:+ """Parse rare boolean data from snapshot - returns True if index is in the rare data."""+ return index in rare_data['index']+++def _parse_computed_styles(strings: list[str], style_indices: list[int]) -> dict[str, str]:+ """Parse computed styles from layout tree using string indices."""+ styles = {}+ for i, style_index in enumerate(style_indices):+ if i < len(REQUIRED_COMPUTED_STYLES) and 0 <= style_index < len(strings):+ styles[REQUIRED_COMPUTED_STYLES[i]] = strings[style_index]+ return styles+++def _is_element_visible(+ bounding_box: dict[str, float], computed_styles: dict[str, str], viewport_width: float, viewport_height: float+) -> bool:+ """Determine if an element is visible. More permissive - considers elements visible if they start anywhere on the page."""+ # Check if element has zero dimensions+ if bounding_box['width'] <= 0 or bounding_box['height'] <= 0:+ return False++ # Check CSS visibility properties+ display = computed_styles.get('display', '').lower()+ visibility = computed_styles.get('visibility', '').lower()+ opacity = computed_styles.get('opacity', '1')++ if display == 'none' or visibility == 'hidden':+ return False++ try:+ if float(opacity) <= 0:+ return False+ except (ValueError, TypeError):+ pass++ # More permissive visibility - element is visible if it has any presence on the page+ # and intersects with the viewport area (including elements that start at the beginning)+ elem_right = bounding_box['x'] + bounding_box['width']+ elem_bottom = bounding_box['y'] + bounding_box['height']++ # Element is visible if it has any intersection with the page area+ # This includes elements that start at x=0, y=0 (beginning of page)+ return elem_right > 0 and elem_bottom > 0 and bounding_box['x'] < viewport_width and bounding_box['y'] < viewport_height+++def build_snapshot_lookup(+ snapshot: CaptureSnapshotReturns, viewport_width: float, viewport_height: float+) -> dict[int, EnhancedSnapshotNode]:+ """Build a lookup table of backend node ID to enhanced snapshot data with everything calculated upfront."""+ snapshot_lookup: dict[int, EnhancedSnapshotNode] = {}++ if not snapshot['documents']:+ return snapshot_lookup++ document: DocumentSnapshot = snapshot['documents'][0]+ strings = snapshot['strings']+ nodes: NodeTreeSnapshot = document['nodes']+ layout: LayoutTreeSnapshot = document['layout']++ # Build backend node id to snapshot index lookup+ backend_node_to_snapshot_index = {}+ if 'backendNodeId' in nodes:+ for i, backend_node_id in enumerate(nodes['backendNodeId']):+ backend_node_to_snapshot_index[backend_node_id] = i++ # Build snapshot lookup for each backend node id+ for backend_node_id, snapshot_index in backend_node_to_snapshot_index.items():+ is_clickable = None+ if 'isClickable' in nodes:+ is_clickable = _parse_rare_boolean_data(nodes['isClickable'], snapshot_index)++ # Find corresponding layout node+ cursor_style = None+ is_visible = None+ bounding_box = None+ computed_styles = {}++ # Look for layout tree node that corresponds to this snapshot node+ for layout_idx, node_index in enumerate(layout.get('nodeIndex', [])):+ if node_index == snapshot_index and layout_idx < len(layout.get('bounds', [])):+ # Parse bounding box+ bounds = layout['bounds'][layout_idx]+ if len(bounds) >= 4:+ bounding_box = {'x': bounds[0], 'y': bounds[1], 'width': bounds[2], 'height': bounds[3]}++ # Parse computed styles for this layout node+ if layout_idx < len(layout.get('styles', [])):+ style_indices = layout['styles'][layout_idx]+ computed_styles = _parse_computed_styles(strings, style_indices)+ cursor_style = computed_styles.get('cursor')++ # Calculate visibility immediately if we have bounding box+ if bounding_box and computed_styles:+ is_visible = _is_element_visible(bounding_box, computed_styles, viewport_width, viewport_height)++ break++ snapshot_lookup[backend_node_id] = EnhancedSnapshotNode(+ is_clickable=is_clickable,+ cursor_style=cursor_style,+ is_visible=is_visible,+ bounding_box=bounding_box,+ computed_styles=computed_styles if computed_styles else None,+ )++ return snapshot_lookupdiff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.pyindex 8f2668cd0..9a0a4b719 100644--- a/browser_use/dom/playground/tree.py+++ b/browser_use/dom/playground/tree.py@@ -35,6 +35,27 @@ async def main():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++ 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)++ 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()diff --git a/browser_use/dom/a11y/service.py b/browser_use/dom/serializer.pysimilarity index 100%rename from browser_use/dom/a11y/service.pyrename to browser_use/dom/serializer.pydiff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 8f09a2740..c450c10b6 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -9,6 +9,10 @@ from cdp_use.cdp.dom.types import Node, ShadowRootTypefrom cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturnsfrom browser_use.browser import Browser+from browser_use.dom.enhanced_snapshot import (+ REQUIRED_COMPUTED_STYLES,+ build_snapshot_lookup,+)from browser_use.dom.views import EnhancedAXNode, EnhancedAXProperty, EnhancedDOMTreeNode, NodeType@@ -63,6 +67,7 @@ class DOMService:await cdp_client.send.DOM.enable(session_id=session_id)await cdp_client.send.Accessibility.enable(session_id=session_id)await cdp_client.send.DOMSnapshot.enable(session_id=session_id)+ await cdp_client.send.Page.enable(session_id=session_id)return session_id@@ -96,7 +101,25 @@ class DOMService:)return enhanced_ax_node- def _build_enhanced_dom_tree(+ async def _get_viewport_size(self) -> tuple[float, float]:+ """Get viewport dimensions using CDP."""+ try:+ cdp_client = await self._get_cdp_client()+ session_id = await self._get_current_page_session_id()++ # Get the layout metrics which includes the visual viewport+ metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)+ visual_viewport = metrics.get('visualViewport', {})++ width = visual_viewport.get('clientWidth', 1920.0)+ height = visual_viewport.get('clientHeight', 1080.0)++ return float(width), float(height)+ except Exception:+ # Fallback to default viewport size+ return 1920.0, 1080.0++ async def _build_enhanced_dom_tree(self, dom_tree: GetDocumentReturns, ax_tree: GetFullAXTreeReturns, snapshot: CaptureSnapshotReturns) -> EnhancedDOMTreeNode:ax_tree_lookup: dict[int, AXNode] = {@@ -106,6 +129,12 @@ class DOMService:enhanced_dom_tree_node_lookup: dict[int, EnhancedDOMTreeNode] = {}""" NodeId (NOT backend node id) -> enhanced dom tree node""" # way to get the parent/content node+ # Get viewport dimensions first for visibility calculation+ viewport_width, viewport_height = await self._get_viewport_size()++ # Parse snapshot data with everything calculated upfront+ snapshot_lookup = build_snapshot_lookup(snapshot, viewport_width, viewport_height)+def _construct_enhanced_node(node: Node) -> EnhancedDOMTreeNode:# memoize the mf (I don't know if some nodes are duplicated)if node['nodeId'] in enhanced_dom_tree_node_lookup:@@ -146,6 +175,7 @@ class DOMService:parent_node=None,children_nodes=None,ax_node=enhanced_ax_node,+ snapshot_node=snapshot_lookup.get(node['backendNodeId'], None),)enhanced_dom_tree_node_lookup[node['nodeId']] = dom_tree_node@@ -183,33 +213,7 @@ class DOMService:snapshot_request = cdp_client.send.DOMSnapshot.captureSnapshot(params={- 'computedStyles': [- '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',- ],+ 'computedStyles': REQUIRED_COMPUTED_STYLES,'includePaintOrder': True,'includeDOMRects': True,'includeBlendedBackgroundColors': False,@@ -233,7 +237,7 @@ class DOMService:snapshot, dom_tree, ax_tree = await self._get_all_trees()start = time.time()- enhanced_dom_tree = self._build_enhanced_dom_tree(dom_tree, ax_tree, snapshot)+ enhanced_dom_tree = await self._build_enhanced_dom_tree(dom_tree, ax_tree, snapshot)end = time.time()print(f'Time taken to build enhanced dom tree: {end - start} seconds')diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 79105b04b..6881e11d1 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -81,7 +81,15 @@ class EnhancedAXNode:@dataclass(slots=True)class EnhancedSnapshotNode:- pass+ """Snapshot data extracted from DOMSnapshot for enhanced functionality."""++ is_clickable: bool | None+ is_visible: bool | None+ cursor_style: str | None+ bounding_box: dict[str, float] | None+ """Bounding box with x, y, width, height in viewport coordinates"""+ computed_styles: dict[str, str] | None+ """Computed styles from the layout tree"""@dataclass(slots=True)@@ -136,6 +144,13 @@ class EnhancedDOMTreeNode:# region - AX Node dataax_node: EnhancedAXNode | None+ # endregion - AX Node data++ # region - Snapshot Node data+ snapshot_node: EnhancedSnapshotNode | None++ # endregion - Snapshot Node data+def __json__(self) -> dict:"""Serializes the node and its descendants to a dictionary, omitting parent references."""return {@@ -150,9 +165,10 @@ class EnhancedDOMTreeNode:'content_document': self.content_document.__json__() if self.content_document else None,'shadow_root_type': self.shadow_root_type.value if self.shadow_root_type else None,'ax_node': asdict(self.ax_node) if self.ax_node else None,+ 'snapshot_node': asdict(self.snapshot_node) if self.snapshot_node else None,# these two in the end, so it's easier to read json- 'children_nodes': [c.__json__() for c in self.children_nodes] if self.children_nodes else [],'shadow_roots': [r.__json__() for r in self.shadow_roots] if self.shadow_roots else [],+ 'children_nodes': [c.__json__() for c in self.children_nodes] if self.children_nodes else [],}