Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

wip iframes, wrong highlights

Gregor Žunič8e707d66d07c
diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.py
index aa40cb548..b009cf1f3 100644
--- a/browser_use/dom/debug/highlights.py
+++ b/browser_use/dom/debug/highlights.py
@@ -7,57 +7,6 @@ from browser_use.dom.service import DomService
from browser_use.dom.views import DOMSelectorMap
-def analyze_element_interactivity(element: dict) -> dict:
- """Analyze why an element is considered interactive and assign confidence level."""
- element_type = element['element_name'].lower()
- attributes = element.get('attributes', {})
-
- # Default reasoning structure
- reasoning = {'confidence': 'LOW', 'primary_reason': 'unknown', 'element_type': element_type, 'reasons': []}
-
- # High confidence elements
- if element_type in ['button', 'a', 'input', 'select', 'textarea']:
- reasoning['confidence'] = 'HIGH'
- reasoning['primary_reason'] = 'semantic_element'
- reasoning['reasons'].append(f'Semantic interactive element: {element_type}')
-
- # Check for interactive attributes
- interactive_attrs = ['onclick', 'onchange', 'href', 'type', 'role']
- found_attrs = [attr for attr in interactive_attrs if attr in attributes]
- if found_attrs:
- if reasoning['confidence'] != 'HIGH':
- reasoning['confidence'] = 'HIGH' if element_type in ['button', 'a'] else 'MEDIUM'
- reasoning['primary_reason'] = 'interactive_attributes'
- reasoning['reasons'].append(f'Interactive attributes: {", ".join(found_attrs)}')
-
- # Check for ARIA roles
- role = attributes.get('role', '').lower()
- if role in ['button', 'link', 'checkbox', 'radio', 'menuitem', 'tab']:
- reasoning['confidence'] = 'HIGH'
- reasoning['primary_reason'] = 'aria_role'
- reasoning['reasons'].append(f'Interactive ARIA role: {role}')
-
- # Check if marked as clickable from snapshot
- if element.get('is_clickable'):
- if reasoning['confidence'] == 'LOW':
- reasoning['confidence'] = 'MEDIUM'
- reasoning['reasons'].append('Marked as clickable in DOM snapshot')
-
- # Check for valid bounding box
- if element.get('width', 0) > 0 and element.get('height', 0) > 0:
- reasoning['reasons'].append(f'Valid bounding box: {element["width"]}x{element["height"]}')
- else:
- reasoning['confidence'] = 'LOW'
- reasoning['reasons'].append('Invalid or missing bounding box')
-
- # Fallback reasoning
- if not reasoning['reasons']:
- reasoning['reasons'].append('Element found in selector map')
- reasoning['primary_reason'] = 'selector_mapped'
-
- return reasoning
-
-
def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -> list[dict]:
"""Convert DOMSelectorMap to the format expected by the highlighting script."""
elements = []
@@ -92,10 +41,6 @@ def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -
else node.node_value[:50],
}
- # Analyze why this element is interactive
- reasoning = analyze_element_interactivity(element)
- element['reasoning'] = reasoning
-
elements.append(element)
else:
# Skip elements without valid bounding boxes for now
diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.py
index 28a3ceaa0..0fdd5c50b 100644
--- a/browser_use/dom/enhanced_snapshot.py
+++ b/browser_use/dom/enhanced_snapshot.py
@@ -7,7 +7,6 @@ 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,
@@ -123,93 +122,108 @@ def build_snapshot_lookup(
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
- paint_order = None
- client_rects = None
- stacking_contexts = None
- 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:
- # IMPORTANT: CDP coordinates are in device pixels, convert to CSS pixels
- # by dividing by the device pixel ratio
- raw_x, raw_y, raw_width, raw_height = bounds[0], bounds[1], bounds[2], bounds[3]
-
- # Apply device pixel ratio scaling to convert device pixels to CSS pixels
- bounding_box = DOMRect(
- x=raw_x / device_pixel_ratio,
- y=raw_y / device_pixel_ratio,
- width=raw_width / device_pixel_ratio,
- height=raw_height / device_pixel_ratio,
- )
-
- # 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')
-
- # Extract paint order if available
- if layout_idx < len(layout.get('paintOrders', [])):
- paint_order = layout.get('paintOrders', [])[layout_idx]
-
- # Extract client rects if available
- client_rects_data = layout.get('clientRects', [])
- if layout_idx < len(client_rects_data):
- client_rect_data = client_rects_data[layout_idx]
- if client_rect_data and len(client_rect_data) >= 4:
- client_rects = DOMRect(
- x=client_rect_data[0],
- y=client_rect_data[1],
- width=client_rect_data[2],
- height=client_rect_data[3],
+
+ for document in snapshot['documents']:
+ 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
+ paint_order = None
+ client_rects = None
+ scroll_rects = None
+ stacking_contexts = None
+ 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:
+ # IMPORTANT: CDP coordinates are in device pixels, convert to CSS pixels
+ # by dividing by the device pixel ratio
+ raw_x, raw_y, raw_width, raw_height = bounds[0], bounds[1], bounds[2], bounds[3]
+
+ # Apply device pixel ratio scaling to convert device pixels to CSS pixels
+ bounding_box = DOMRect(
+ x=raw_x / device_pixel_ratio,
+ y=raw_y / device_pixel_ratio,
+ width=raw_width / device_pixel_ratio,
+ height=raw_height / device_pixel_ratio,
+ )
+
+ # 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')
+
+ # Extract paint order if available
+ if layout_idx < len(layout.get('paintOrders', [])):
+ paint_order = layout.get('paintOrders', [])[layout_idx]
+
+ # Extract client rects if available
+ client_rects_data = layout.get('clientRects', [])
+ if layout_idx < len(client_rects_data):
+ client_rect_data = client_rects_data[layout_idx]
+ if client_rect_data and len(client_rect_data) >= 4:
+ client_rects = DOMRect(
+ x=client_rect_data[0],
+ y=client_rect_data[1],
+ width=client_rect_data[2],
+ height=client_rect_data[3],
+ )
+
+ # Extract scroll rects if available
+ scroll_rects_data = layout.get('scrollRects', [])
+ if layout_idx < len(scroll_rects_data):
+ scroll_rect_data = scroll_rects_data[layout_idx]
+ if scroll_rect_data and len(scroll_rect_data) >= 4:
+ scroll_rects = DOMRect(
+ x=scroll_rect_data[0],
+ y=scroll_rect_data[1],
+ width=scroll_rect_data[2],
+ height=scroll_rect_data[3],
+ )
+
+ # Extract stacking contexts if available
+ if layout_idx < len(layout.get('stackingContexts', [])):
+ stacking_contexts = layout.get('stackingContexts', {}).get('index', [])[layout_idx]
+
+ # Calculate scroll-aware visibility if we have bounding box
+ if bounding_box and computed_styles:
+ is_visible = _is_element_visible(
+ bounding_box, computed_styles, viewport_width, viewport_height, scroll_x, scroll_y
)
- # Extract stacking contexts if available
- if layout_idx < len(layout.get('stackingContexts', [])):
- stacking_contexts = layout.get('stackingContexts', {}).get('index', [])[layout_idx]
-
- # Calculate scroll-aware visibility if we have bounding box
- if bounding_box and computed_styles:
- is_visible = _is_element_visible(
- bounding_box, computed_styles, viewport_width, viewport_height, scroll_x, scroll_y
- )
-
- break
-
- snapshot_lookup[backend_node_id] = EnhancedSnapshotNode(
- is_clickable=is_clickable,
- cursor_style=cursor_style,
- is_visible=is_visible,
- bounds=bounding_box,
- # clientRects=client_rects,
- computed_styles=computed_styles if computed_styles else None,
- paint_order=paint_order,
- stacking_contexts=stacking_contexts,
- )
+ break
+
+ snapshot_lookup[backend_node_id] = EnhancedSnapshotNode(
+ is_clickable=is_clickable,
+ cursor_style=cursor_style,
+ is_visible=is_visible,
+ bounds=bounding_box,
+ clientRects=client_rects,
+ scrollRects=scroll_rects,
+ computed_styles=computed_styles if computed_styles else None,
+ paint_order=paint_order,
+ stacking_contexts=stacking_contexts,
+ )
return snapshot_lookup
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.py
index 24048d887..a94486ad2 100644
--- a/browser_use/dom/playground/extraction.py
+++ b/browser_use/dom/playground/extraction.py
@@ -33,7 +33,7 @@ async def test_focus_vs_all_elements():
# 10 Sample websites with various interactive elements
sample_websites = [
- 'https://v0-website-with-clickable-elements.vercel.app/shadow-dom',
+ 'https://v0-website-with-clickable-elements.vercel.app/iframe-buttons',
'https://www.google.com/travel/flights',
'https://www.amazon.com/s?k=laptop',
'https://github.com/trending',
diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.py
index a9e43f7ff..18ba23e6f 100644
--- a/browser_use/dom/playground/tree.py
+++ b/browser_use/dom/playground/tree.py
@@ -4,15 +4,25 @@ import time
import aiofiles
-from browser_use.browser import BrowserSession
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.types import ViewportSize
+from browser_use.dom.debug.highlights import inject_highlighting_script, remove_highlighting_script
from browser_use.dom.service import DomService
async def main():
# async with async_playwright() as p:
# playwright_browser = await p.chromium.launch(args=['--remote-debugging-port=9222'], headless=False)
- browser = BrowserSession()
-
+ browser = BrowserSession(
+ browser_profile=BrowserProfile(
+ # executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ window_size=ViewportSize(width=1100, height=1000),
+ disable_security=True,
+ wait_for_network_idle_page_load_time=1,
+ headless=False,
+ args=['--incognito'],
+ ),
+ )
# async with httpx.AsyncClient() as client:
# version_info = await client.get('http://localhost:9222/json/version')
# browser.cdp_url = version_info.json()['webSocketDebuggerUrl']
@@ -22,74 +32,77 @@ async def main():
# 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.navigate('https://v0-website-with-clickable-elements.vercel.app/iframe-buttons')
+
await browser._wait_for_page_and_frames_load()
page = await browser.get_current_page()
- dom_service = DomService(browser, page)
-
while True:
- start = time.time()
- dom_tree, dom_timing = await dom_service.get_dom_tree()
- end = time.time()
- print(f'Time taken: {end - start} seconds')
+ async with DomService(browser, page) as dom_service:
+ await remove_highlighting_script(dom_service)
+
+ start = time.time()
+ dom_tree, dom_timing = 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'
+ )
- serialized_dom_state, timing_info = await dom_service.get_serialized_dom_tree()
+ serialized_dom_state, timing_info = await dom_service.get_serialized_dom_tree()
- async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:
- await f.write(serialized_dom_state.llm_representation())
+ async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:
+ await f.write(serialized_dom_state.llm_representation())
- # print(serialized)
- print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')
+ # print(serialized)
+ print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')
- # print(selector_map)
+ start = time.time()
+ snapshot, dom_tree, ax_tree, _ = await dom_service._get_all_trees()
+ end = time.time()
+ print(f'Time taken: {end - start} seconds')
- # 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/snapshot.json', 'w') as f:
+ await f.write(json.dumps(snapshot, indent=1))
- # 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/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))
- # 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')
- # 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')
+ await inject_highlighting_script(dom_service, serialized_dom_state.selector_map)
- input('Done. Press Enter to continue...')
+ input('Done. Press Enter to continue...')
if __name__ == '__main__':
diff --git a/browser_use/dom/serializer/serializer.py b/browser_use/dom/serializer/serializer.py
index eed74af99..d45135b32 100644
--- a/browser_use/dom/serializer/serializer.py
+++ b/browser_use/dom/serializer/serializer.py
@@ -102,6 +102,15 @@ class DOMTreeSerializer:
if node.node_name.lower() in DISABLED_ELEMENTS:
return None
+ if node.node_name == 'IFRAME':
+ if node.content_document:
+ simplified = SimplifiedNode(original_node=node, children=[])
+ for child in node.content_document.children:
+ simplified_child = self._create_simplified_tree(child)
+ if simplified_child:
+ simplified.children.append(simplified_child)
+ return simplified
+
# Use enhanced scoring for inclusion decision
is_interactive = self._is_interactive_cached(node)
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 8729cc2b4..ff810a1a6 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -245,6 +245,9 @@ class DomService:
if 'contentDocument' in node and node['contentDocument']:
dom_tree_node.content_document = _construct_enhanced_node(node['contentDocument']) # maybe new maybe not, idk
+ dom_tree_node.content_document.parent_node = (
+ dom_tree_node # forcefully set the parent node to the content document node (helps traverse the tree)
+ )
if 'shadowRoots' in node and node['shadowRoots']:
dom_tree_node.shadow_roots = []
@@ -265,6 +268,39 @@ class DomService:
return enhanced_dom_tree_node
+ async def _get_ax_tree_for_all_frames(self, cdp_client: CDPClient, session_id: str) -> GetFullAXTreeReturns:
+ """Recursively collect all frames and merge their accessibility trees into a single array."""
+ frame_tree = await cdp_client.send.Page.getFrameTree(session_id=session_id)
+
+ def collect_all_frame_ids(frame_tree_node) -> list[str]:
+ """Recursively collect all frame IDs from the frame tree."""
+ frame_ids = [frame_tree_node['frame']['id']]
+
+ if 'childFrames' in frame_tree_node and frame_tree_node['childFrames']:
+ for child_frame in frame_tree_node['childFrames']:
+ frame_ids.extend(collect_all_frame_ids(child_frame))
+
+ return frame_ids
+
+ # Collect all frame IDs recursively
+ all_frame_ids = collect_all_frame_ids(frame_tree['frameTree'])
+
+ # Get accessibility tree for each frame
+ ax_tree_requests = []
+ for frame_id in all_frame_ids:
+ ax_tree_request = cdp_client.send.Accessibility.getFullAXTree(params={'frameId': frame_id}, session_id=session_id)
+ ax_tree_requests.append(ax_tree_request)
+
+ # Wait for all requests to complete
+ ax_trees = await asyncio.gather(*ax_tree_requests)
+
+ # Merge all AX nodes into a single array
+ merged_nodes: list[AXNode] = []
+ for ax_tree in ax_trees:
+ merged_nodes.extend(ax_tree['nodes'])
+
+ return {'nodes': merged_nodes}
+
async def _get_all_trees(self) -> tuple[CaptureSnapshotReturns, GetDocumentReturns, GetFullAXTreeReturns, dict[str, float]]:
if not self.browser.cdp_url:
raise ValueError('CDP URL is not set')
@@ -285,7 +321,7 @@ class DomService:
dom_tree_request = cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)
- ax_tree_request = cdp_client.send.Accessibility.getFullAXTree(session_id=session_id)
+ ax_tree_request = self._get_ax_tree_for_all_frames(cdp_client, session_id)
start = time.time()
snapshot, dom_tree, ax_tree = await asyncio.gather(snapshot_request, dom_tree_request, ax_tree_request)
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index e471b0021..2b46549f8 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -113,13 +113,18 @@ class EnhancedSnapshotNode:
Typical use: Quick hit-test that doesn't care about scroll position.
"""
- # clientRects: DOMRect | None
+ clientRects: DOMRect | None
"""
Viewport coordinates (origin = top-left of the visible scrollport).
Equivalent JS API: element.getClientRects() / getBoundingClientRect().
Typical use: Pixel-perfect hit-testing on screen, taking current scroll into account.
"""
+ scrollRects: DOMRect | None
+ """
+ Scrollable area of the element.
+ """
+
computed_styles: dict[str, str] | None
"""Computed styles from the layout tree"""
paint_order: int | None