Skip to content

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

stash

Matic Zavadlal0acce1fc1fca
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index a019f675c..5e0d02f33 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -5,28 +5,22 @@
viewportExpansion: 0,
}
) => {
- const getMemoryUsage = () => {
- if (window.performance && window.performance.memory) {
- const memory = window.performance.memory;
- return {
- usedJSHeapSize: Math.round(memory.usedJSHeapSize / (1024 * 1024)), // MB
- totalJSHeapSize: Math.round(memory.totalJSHeapSize / (1024 * 1024)), // MB
- jsHeapSizeLimit: Math.round(memory.jsHeapSizeLimit / (1024 * 1024)), // MB
- };
- }
- return null;
- };
-
- const memory = [];
-
- memory.push(["start", getMemoryUsage()]);
-
const { doHighlightElements, focusHighlightIndex, viewportExpansion } = args;
let highlightIndex = 0; // Reset highlight index
+ /**
+ * Hash map of DOM nodes indexed by their highlight index.
+ */
+ const DOM_HASH_MAP = {};
+
+ const ID = { current: 0 };
+
// Quick check to confirm the script receives focusHighlightIndex
console.log("focusHighlightIndex:", focusHighlightIndex);
+ /**
+ * Highlights an element in the DOM and returns the index of the next element.
+ */
function highlightElement(element, index, parentIframe = null) {
// Create or get highlight container
let container = document.getElementById("playwright-highlight-container");
@@ -129,7 +123,9 @@
return index + 1;
}
- // Helper function to generate XPath as a tree
+ /**
+ * Returns an XPath tree string for an element.
+ */
function getXPathTree(element, stopAtBoundary = true) {
const segments = [];
let currentElement = element;
@@ -178,7 +174,9 @@
return !leafElementDenyList.has(element.tagName.toLowerCase());
}
- // Helper function to check if element is interactive
+ /**
+ * Checks if an element is interactive.
+ */
function isInteractiveElement(element) {
// Immediately return false for body tag
if (element.tagName.toLowerCase() === "body") {
@@ -361,7 +359,9 @@
);
}
- // Helper function to check if element is visible
+ /**
+ * Checks if an element is visible.
+ */
function isElementVisible(element) {
const style = window.getComputedStyle(element);
return (
@@ -372,7 +372,9 @@
);
}
- // Helper function to check if element is the top element at its position
+ /**
+ * Checks if an element is the top element at its position.
+ */
function isTopElement(element) {
// Find the correct document context and root element
let doc = element.ownerDocument;
@@ -474,7 +476,9 @@
}
}
- // Helper function to check if text node is visible
+ /**
+ * Checks if a text node is visible.
+ */
function isTextNodeVisible(textNode) {
const range = document.createRange();
range.selectNodeContents(textNode);
@@ -492,7 +496,10 @@
);
}
- // Function to traverse the DOM and create nested JSON
+ /**
+ * Creates a node data object for a given node and its descendants and returns
+ * the identifier of the node in the hash map or null if the node is not accepted.
+ */
function buildDomTree(node, parentIframe = null) {
if (!node) {
return null;
@@ -502,11 +509,15 @@
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.textContent.trim();
if (textContent && isTextNodeVisible(node)) {
- return {
+ const id = ID.current++;
+
+ DOM_HASH_MAP[id] = {
type: "TEXT_NODE",
text: textContent,
isVisible: true,
};
+
+ return id;
}
return null;
}
@@ -647,29 +658,33 @@
try {
const iframeDoc = node.contentDocument || node.contentWindow.document;
if (iframeDoc) {
- const iframeChildren = Array.from(iframeDoc.body.childNodes).map(
- (child) => buildDomTree(child, node)
- );
- nodeData.children.push(...iframeChildren);
+ for (const child of iframeDoc.body.childNodes) {
+ const domElement = buildDomTree(child, node);
+ if (domElement) {
+ nodeData.children.push(domElement);
+ }
+ }
}
} catch (e) {
console.warn("Unable to access iframe:", node);
}
} else {
- const children = Array.from(node.childNodes).map((child) =>
- buildDomTree(child, parentIframe)
- );
- nodeData.children.push(...children);
+ for (const child of node.childNodes) {
+ const domElement = buildDomTree(child, parentIframe);
+ if (domElement) {
+ nodeData.children.push(domElement);
+ }
+ }
}
- return nodeData;
- }
-
- memory.push(["postbuild", getMemoryUsage()]);
+ // NOTE: We register the node to the hash map.
+ const id = ID.current++;
+ DOM_HASH_MAP[id] = nodeData;
- const tree = buildDomTree(document.body);
+ return id;
+ }
- memory.push(["posttree", getMemoryUsage()]);
+ const rootId = buildDomTree(document.body);
- return { ...tree, memory };
+ return { rootId, map: DOM_HASH_MAP };
};
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index ced726c95..02924855e 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -1,11 +1,9 @@
import logging
-import time
from importlib import resources
from typing import Optional
-from memory_profiler import memory_usage
+from memory_profiler import profile
from playwright.async_api import Page
-from pympler import asizeof
from browser_use.dom.history_tree_processor.view import Coordinates
from browser_use.dom.views import (
@@ -28,6 +26,8 @@ class DomService:
self._iter = 0
+ self.js_code = resources.read_text('browser_use.dom', 'buildDomTree.js')
+
# region - Clickable elements
async def get_clickable_elements(
self,
@@ -40,164 +40,138 @@ class DomService:
return DOMState(element_tree=element_tree, selector_map=selector_map)
+ def _create_selector_map(self, element_tree: DOMElementNode) -> SelectorMap:
+ selector_map = {}
+
+ def process_node(node: DOMBaseNode):
+ if isinstance(node, DOMElementNode):
+ if node.highlight_index is not None:
+ selector_map[node.highlight_index] = node
+
+ for child in node.children:
+ process_node(child)
+
+ process_node(element_tree)
+
+ return selector_map
+
+ @profile
async def _build_dom_tree(
self,
highlight_elements: bool,
focus_element: int,
viewport_expansion: int,
) -> DOMElementNode:
- js_code = resources.read_text('browser_use.dom', 'buildDomTree.js')
+ self._iter += 1
+ logger.info(f'Iteration {self._iter} --------------------------------')
+ # NOTE: We execute JS code in the browser to extract important DOM information.
+ # The returned hash map contains information about the DOM tree and the
+ # relationship between the DOM elements.
args = {
'doHighlightElements': highlight_elements,
'focusHighlightIndex': focus_element,
'viewportExpansion': viewport_expansion,
}
+ eval_page = await self.page.evaluate(self.js_code, args)
- self._iter += 1
- logger.info(f'Iteration {self._iter} --------------------------------')
-
- mem_before = memory_usage(-1, interval=0.1, timeout=1)[0]
+ js_node_map = eval_page['map']
+ js_root_id = eval_page['rootId']
- logger.info(f'Eval Memory Usage: {mem_before} MB')
- eval_page = await self.page.evaluate(js_code, args) # This is quite big, so be careful
+ node_map = {}
- start_time = time.time()
+ for _id, node_data in js_node_map.items():
+ id = str(_id)
+ node, children_ids = self._parse_node(node_data)
+ if node is None:
+ print(f'Node {id} is None!')
+ print(node_data)
+ continue
+ node_map[id] = node
- eval_page_deep_size = asizeof.asizeof(eval_page)
- logger.info(f'Deep size of eval_page: {eval_page_deep_size / 1024 / 1024:.2f} MB')
+ # NOTE: We know that we are building the tree bottom up!
+ for _child_id in children_ids:
+ child_id = str(_child_id)
+ child_node = node_map[child_id]
- mem_after = memory_usage(-1, interval=0.1, timeout=1)[0]
+ if child_id not in node_map:
+ print(f'Child node {child_id} not found!')
+ continue
- logger.info(f'Eval Memory Usage: {mem_after} MB')
+ node_map[id].children.append(child_node)
- html_to_dict = self._parse_node_iterative(eval_page)
- mem_after = memory_usage(-1, interval=0.1, timeout=1)[0]
- logger.info(f'Parse Memory Usage: {mem_after} MB')
+ html_to_dict = node_map[str(js_root_id)]
if html_to_dict is None or not isinstance(html_to_dict, DOMElementNode):
raise ValueError('Failed to parse HTML to dictionary')
- html_to_dict_deep_size = asizeof.asizeof(html_to_dict)
- logger.info(f'Deep size of html_to_dict: {html_to_dict_deep_size / 1024 / 1024:.2f} MB')
-
- end_time = time.time()
- logger.info(f'Time taken: {end_time - start_time} seconds')
-
return html_to_dict
- def _create_selector_map(self, element_tree: DOMElementNode) -> SelectorMap:
- selector_map = {}
-
- def process_node(node: DOMBaseNode):
- if isinstance(node, DOMElementNode):
- if node.highlight_index is not None:
- selector_map[node.highlight_index] = node
-
- for child in node.children:
- process_node(child)
-
- process_node(element_tree)
- return selector_map
-
- # @profile
- def _parse_node_iterative(
+ def _parse_node(
self,
- root_data: dict,
- parent: Optional[DOMElementNode] = None,
- ) -> Optional[DOMBaseNode]:
- if not root_data:
- return None
+ node_data: dict,
+ ) -> tuple[Optional[DOMBaseNode], list[int]]:
+ if not node_data:
+ return None, []
# Process text nodes immediately
- if root_data.get('type') == 'TEXT_NODE':
+ if node_data.get('type') == 'TEXT_NODE':
text_node = DOMTextNode(
- text=root_data['text'],
- is_visible=root_data['isVisible'],
- parent=parent,
+ text=node_data['text'],
+ is_visible=node_data['isVisible'],
+ parent=None,
)
- return text_node
-
- # A helper to create the DOMElementNode like in your original code
- def create_element_node(node_data: dict, parent: Optional[DOMElementNode]) -> DOMElementNode:
- # Process coordinates if they exist for element nodes
- viewport_coordinates = None
- page_coordinates = None
- viewport_info = None
-
- if 'viewportCoordinates' in node_data:
- viewport_coordinates = CoordinateSet(
- top_left=Coordinates(**node_data['viewportCoordinates']['topLeft']),
- top_right=Coordinates(**node_data['viewportCoordinates']['topRight']),
- bottom_left=Coordinates(**node_data['viewportCoordinates']['bottomLeft']),
- bottom_right=Coordinates(**node_data['viewportCoordinates']['bottomRight']),
- center=Coordinates(**node_data['viewportCoordinates']['center']),
- width=node_data['viewportCoordinates']['width'],
- height=node_data['viewportCoordinates']['height'],
- )
- if 'pageCoordinates' in node_data:
- page_coordinates = CoordinateSet(
- top_left=Coordinates(**node_data['pageCoordinates']['topLeft']),
- top_right=Coordinates(**node_data['pageCoordinates']['topRight']),
- bottom_left=Coordinates(**node_data['pageCoordinates']['bottomLeft']),
- bottom_right=Coordinates(**node_data['pageCoordinates']['bottomRight']),
- center=Coordinates(**node_data['pageCoordinates']['center']),
- width=node_data['pageCoordinates']['width'],
- height=node_data['pageCoordinates']['height'],
- )
- if 'viewport' in node_data:
- viewport_info = ViewportInfo(
- scroll_x=node_data['viewport']['scrollX'],
- scroll_y=node_data['viewport']['scrollY'],
- width=node_data['viewport']['width'],
- height=node_data['viewport']['height'],
- )
-
- return DOMElementNode(
- tag_name=node_data['tagName'],
- xpath=node_data['xpath'],
- attributes=node_data.get('attributes', {}),
- children=[], # initially empty
- is_visible=node_data.get('isVisible', False),
- is_interactive=node_data.get('isInteractive', False),
- is_top_element=node_data.get('isTopElement', False),
- highlight_index=node_data.get('highlightIndex'),
- shadow_root=node_data.get('shadowRoot', False),
- parent=parent,
- viewport_coordinates=viewport_coordinates,
- page_coordinates=page_coordinates,
- viewport_info=viewport_info,
+ return text_node, []
+
+ # Process coordinates if they exist for element nodes
+ viewport_coordinates = None
+ page_coordinates = None
+ viewport_info = None
+
+ if 'viewportCoordinates' in node_data:
+ viewport_coordinates = CoordinateSet(
+ top_left=Coordinates(**node_data['viewportCoordinates']['topLeft']),
+ top_right=Coordinates(**node_data['viewportCoordinates']['topRight']),
+ bottom_left=Coordinates(**node_data['viewportCoordinates']['bottomLeft']),
+ bottom_right=Coordinates(**node_data['viewportCoordinates']['bottomRight']),
+ center=Coordinates(**node_data['viewportCoordinates']['center']),
+ width=node_data['viewportCoordinates']['width'],
+ height=node_data['viewportCoordinates']['height'],
+ )
+ if 'pageCoordinates' in node_data:
+ page_coordinates = CoordinateSet(
+ top_left=Coordinates(**node_data['pageCoordinates']['topLeft']),
+ top_right=Coordinates(**node_data['pageCoordinates']['topRight']),
+ bottom_left=Coordinates(**node_data['pageCoordinates']['bottomLeft']),
+ bottom_right=Coordinates(**node_data['pageCoordinates']['bottomRight']),
+ center=Coordinates(**node_data['pageCoordinates']['center']),
+ width=node_data['pageCoordinates']['width'],
+ height=node_data['pageCoordinates']['height'],
+ )
+ if 'viewport' in node_data:
+ viewport_info = ViewportInfo(
+ scroll_x=node_data['viewport']['scrollX'],
+ scroll_y=node_data['viewport']['scrollY'],
+ width=node_data['viewport']['width'],
+ height=node_data['viewport']['height'],
)
- # Create the root element node
- root_node = create_element_node(root_data, parent)
-
- # Stack will hold tuples of (node_data, DOMElementNode) where
- # node_data is the dict that might have children and DOMElementNode is
- # the parent node to attach those children to.
- stack: list[tuple[dict, DOMElementNode]] = [(root_data, root_node)]
-
- while stack:
- current_data, current_node = stack.pop()
-
- # Iterate over children in order (to maintain ordering, use normal order)
- # If you need the original order in the final children list, you can reverse the order in which you push
- for child_data in current_data.get('children', []):
- if child_data is None:
- continue
-
- if child_data.get('type') == 'TEXT_NODE':
- # Immediately create text nodes and attach them as children
- text_node = DOMTextNode(
- text=child_data['text'],
- is_visible=child_data['isVisible'],
- parent=current_node,
- )
- current_node.children.append(text_node)
- else:
- # Create element node and push it to the stack for further processing
- child_node = create_element_node(child_data, current_node)
- current_node.children.append(child_node)
- stack.append((child_data, child_node))
-
- return root_node
+ element_node = DOMElementNode(
+ tag_name=node_data['tagName'],
+ xpath=node_data['xpath'],
+ attributes=node_data.get('attributes', {}),
+ children=[],
+ is_visible=node_data.get('isVisible', False),
+ is_interactive=node_data.get('isInteractive', False),
+ is_top_element=node_data.get('isTopElement', False),
+ highlight_index=node_data.get('highlightIndex'),
+ shadow_root=node_data.get('shadowRoot', False),
+ parent=None,
+ viewport_coordinates=viewport_coordinates,
+ page_coordinates=page_coordinates,
+ viewport_info=viewport_info,
+ )
+
+ children_ids = node_data.get('children', [])
+
+ return element_node, children_ids