Skip to content

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

nicer types

Gregor Žunič779196d74c8a
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 6984b2761..28b5e2646 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -21,7 +21,7 @@ from browser_use.agent.cloud_events import (
CreateAgentTaskEvent,
UpdateAgentTaskEvent,
)
-from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES
+from browser_use.dom.serializer import DEFAULT_INCLUDE_ATTRIBUTES
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import BaseMessage, UserMessage
from browser_use.tokens.service import TokenCost
@@ -60,7 +60,7 @@ from browser_use.browser.views import BrowserStateSummary
from browser_use.config import CONFIG
from browser_use.controller.registry.views import ActionModel
from browser_use.controller.service import Controller
-from browser_use.dom.views import DOMHistoryElement
+from browser_use.dom.views import DOMInteractedElement
from browser_use.exceptions import LLMException
from browser_use.filesystem.file_system import FileSystem
from browser_use.observability import observe, observe_debug
@@ -1485,7 +1485,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
async def _update_action_indices(
self,
- historical_element: DOMHistoryElement | None,
+ historical_element: DOMInteractedElement | None,
action: ActionModel, # Type this properly based on your action model
browser_state_summary: BrowserStateSummary,
) -> ActionModel | None:
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index ad82a89df..db94fec13 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -17,6 +17,7 @@ from typing import Any, Self
from urllib.parse import urlparse
from browser_use.config import CONFIG
+from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode
from browser_use.observability import observe_debug
from browser_use.utils import _log_pretty_path, _log_pretty_url
@@ -1996,14 +1997,14 @@ class BrowserSession(BaseModel):
# Don't raise the error since this is not critical functionality
@require_initialization
- async def get_dom_element_by_index(self, index: int) -> DOMElementNode | None:
+ async def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
"""Get DOM element by index."""
selector_map = await self.get_selector_map()
return selector_map.get(index)
@require_initialization
@time_execution_async('--click_element_node')
- async def _click_element_node(self, element_node: DOMElementNode) -> str | None:
+ async def _click_element_node(self, element_node: EnhancedDOMTreeNode) -> str | None:
"""
Optimized method to click an element using xpath.
"""
@@ -2089,7 +2090,7 @@ class BrowserSession(BaseModel):
raise e
except Exception as e:
# Final fallback - try clicking by coordinates if available
- if element_node.viewport_coordinates and element_node.viewport_coordinates.center:
+ if element_node.snapshot_node and element_node.snapshot_node.clientRects:
try:
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})'
@@ -3722,7 +3723,7 @@ class BrowserSession(BaseModel):
# region - Helper methods for easier access to the DOM
@observe_debug(name='get_selector_map')
@require_initialization
- async def get_selector_map(self) -> SelectorMap:
+ async def get_selector_map(self) -> DOMSelectorMap:
if self._cached_browser_state_summary is None:
return {}
return self._cached_browser_state_summary.selector_map
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index 7253024ad..cd1635267 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -3,7 +3,7 @@ from typing import Any
from pydantic import BaseModel
-from browser_use.dom.views import DOMHistoryElement, DOMState
+from browser_use.dom.views import DOMInteractedElement, DOMState
# Pydantic
@@ -67,7 +67,7 @@ class BrowserStateHistory:
url: str
title: str
tabs: list[TabInfo]
- interacted_element: list[DOMHistoryElement | None] | list[None]
+ interacted_element: list[DOMInteractedElement | None] | list[None]
screenshot: str | None = None
def to_dict(self) -> dict[str, Any]:
diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.py
index 76d3f0fb4..60ad508ef 100644
--- a/browser_use/dom/enhanced_snapshot.py
+++ b/browser_use/dom/enhanced_snapshot.py
@@ -13,7 +13,7 @@ from cdp_use.cdp.domsnapshot.types import (
RareBooleanData,
)
-from browser_use.dom.views import EnhancedSnapshotNode
+from browser_use.dom.views import DOMRect, EnhancedSnapshotNode
# Only the essential computed styles we actually need
REQUIRED_COMPUTED_STYLES = [
@@ -60,11 +60,11 @@ def _parse_computed_styles(strings: list[str], style_indices: list[int]) -> dict
def _is_element_visible(
- bounding_box: dict[str, float], computed_styles: dict[str, str], viewport_width: float, viewport_height: float
+ bounding_box: DOMRect, 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:
+ if bounding_box.width <= 0 or bounding_box.height <= 0:
return False
# Check CSS visibility properties
@@ -83,12 +83,12 @@ def _is_element_visible(
# 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']
+ 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
+ return elem_right > 0 and elem_bottom > 0 and bounding_box.x < viewport_width and bounding_box.y < viewport_height
def build_snapshot_lookup(
@@ -132,7 +132,7 @@ def build_snapshot_lookup(
# 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]}
+ bounding_box = DOMRect(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', [])):
@@ -149,12 +149,12 @@ def build_snapshot_lookup(
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 = {
- 'x': client_rect_data[0],
- 'y': client_rect_data[1],
- 'width': client_rect_data[2],
- 'height': client_rect_data[3],
- }
+ client_rects = DOMRect(
+ x=client_rect_data[0],
+ y=client_rect_data[1],
+ width=client_rect_data[2],
+ height=client_rect_data[3],
+ )
# Extract stacking contexts if available
if layout_idx < len(layout.get('stackingContexts', [])):
diff --git a/browser_use/dom/serializer.py b/browser_use/dom/serializer.py
index e9b79a352..54124b277 100644
--- a/browser_use/dom/serializer.py
+++ b/browser_use/dom/serializer.py
@@ -4,7 +4,23 @@ from dataclasses import dataclass, field
from cdp_use.cdp.accessibility.types import AXPropertyName
-from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES, EnhancedDOMTreeNode, NodeType
+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)
@@ -40,13 +56,13 @@ class DOMTreeSerializer:
self.root_node = root_node
self._interactive_counter = 1
- self._selector_map: dict[int, EnhancedDOMTreeNode] = {}
+ self._selector_map: DOMSelectorMap = {}
- def serialize_accessible_elements(
- self, include_attributes: list[str] | None = None
- ) -> tuple[str, dict[int, EnhancedDOMTreeNode]]:
+ def serialize_accessible_elements(self, include_attributes: list[str] | None = None) -> tuple[str, DOMSelectorMap]:
"""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
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 22c6e3300..61a5ec82f 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -1,34 +1,9 @@
from dataclasses import asdict, dataclass
from enum import Enum
+from typing import Any
from cdp_use.cdp.accessibility.types import AXPropertyName
from cdp_use.cdp.dom.types import ShadowRootType
-from pydantic import BaseModel
-
-################## TO BE REMOVED
-DEFAULT_INCLUDE_ATTRIBUTES = [
- 'title',
- 'type',
- 'checked',
- 'name',
- 'role',
- 'value',
- 'placeholder',
- 'data-date-format',
- 'alt',
- 'aria-label',
- 'aria-expanded',
- 'data-state',
- 'aria-checked',
-]
-
-
-class DOMNodeAttributes(BaseModel):
- name: str
- value: str
-
-
-################## END TO BE REMOVED
class NodeType(int, Enum):
@@ -79,6 +54,14 @@ class EnhancedAXNode:
properties: list[EnhancedAXProperty] | None
+@dataclass(slots=True)
+class DOMRect:
+ x: float
+ y: float
+ width: float
+ height: float
+
+
@dataclass(slots=True)
class EnhancedSnapshotNode:
"""Snapshot data extracted from DOMSnapshot for enhanced functionality."""
@@ -86,14 +69,14 @@ class EnhancedSnapshotNode:
is_clickable: bool | None
is_visible: bool | None
cursor_style: str | None
- bounds: dict[str, float] | None
+ bounds: DOMRect | None
"""
Document coordinates (origin = top-left of the page, ignores current scroll).
Equivalent JS API: layoutNode.boundingBox in the older API.
Typical use: Quick hit-test that doesn’t care about scroll position.
"""
- clientRects: dict[str, float] | None
+ clientRects: DOMRect | None
"""
Viewport coordinates (origin = top-left of the visible scrollport).
Equivalent JS API: element.getClientRects() / getBoundingClientRect().
@@ -233,10 +216,28 @@ class EnhancedDOMTreeNode:
}
+DOMSelectorMap = dict[int, EnhancedDOMTreeNode]
+
+
@dataclass
class DOMState: #
root: EnhancedDOMTreeNode
-class DOMHistoryElement:
- pass
+@dataclass
+class DOMInteractedElement:
+ node_type: NodeType
+ node_value: str
+ node_name: str
+ attributes: dict[str, str] | None
+
+ x_path: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ 'node_type': self.node_type.value,
+ 'node_value': self.node_value,
+ 'node_name': self.node_name,
+ 'attributes': self.attributes,
+ 'x_path': self.x_path,
+ }