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, started migrating to pure cdp
Gregor Žunič8a2eda182801
diff --git a/browser_use/__init__.py b/browser_use/__init__.pyindex 1635b1e79..14d3df6c2 100644--- a/browser_use/__init__.py+++ b/browser_use/__init__.py@@ -18,7 +18,8 @@ from browser_use.agent.service import Agentfrom browser_use.agent.views import ActionModel, ActionResult, AgentHistoryListfrom browser_use.browser import Browser, BrowserConfig, BrowserContext, BrowserContextConfig, BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controller-from browser_use.dom.service import DomService++# from browser_use.dom.service import DomServicefrom browser_use.llm import (ChatAnthropic,ChatAzureOpenAI,@@ -57,7 +58,7 @@ __all__ = ['BrowserSession','BrowserProfile','Controller',- 'DomService',+ # 'DomService','SystemPrompt','ActionResult','ActionModel',diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex b3d3b9637..6984b2761 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -60,10 +60,7 @@ from browser_use.browser.views import BrowserStateSummaryfrom browser_use.config import CONFIGfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller-from browser_use.dom.history_tree_processor.service import (- DOMHistoryElement,- HistoryTreeProcessor,-)+from browser_use.dom.views import DOMHistoryElementfrom browser_use.exceptions import LLMExceptionfrom browser_use.filesystem.file_system import FileSystemfrom browser_use.observability import observe, observe_debugdiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 379dc7486..da01f9550 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -14,12 +14,13 @@ from uuid_extensions import uuid7strfrom browser_use.agent.message_manager.views import MessageManagerStatefrom browser_use.browser.views import BrowserStateHistoryfrom browser_use.controller.registry.views import ActionModel-from browser_use.dom.history_tree_processor.service import (- DOMElementNode,- DOMHistoryElement,- HistoryTreeProcessor,-)-from browser_use.dom.views import SelectorMap++# from browser_use.dom.history_tree_processor.service import (+# DOMElementNode,+# DOMHistoryElement,+# HistoryTreeProcessor,+# )+# from browser_use.dom.views import SelectorMapfrom browser_use.filesystem.file_system import FileSystemStatefrom browser_use.llm.base import BaseChatModelfrom browser_use.tokens.views import UsageSummarydiff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 68a4596ea..ad82a89df 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -50,9 +50,10 @@ from browser_use.browser.views import (TabInfo,URLNotAllowedError,)-from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor-from browser_use.dom.service import DomService-from browser_use.dom.views import DOMElementNode, SelectorMap++# from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor+# from browser_use.dom.service import DomService+# from browser_use.dom.views import DOMElementNode, SelectorMapfrom browser_use.utils import (is_new_tab_page,match_url_with_domain_pattern,diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex 415ebb0a1..7253024ad 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -3,8 +3,7 @@ from typing import Anyfrom pydantic import BaseModel-from browser_use.dom.history_tree_processor.service import DOMHistoryElement-from browser_use.dom.views import DOMState+from browser_use.dom.views import DOMHistoryElement, DOMState# Pydanticdiff --git a/browser_use/dom/__init__.py b/browser_use/dom/a11y/service.pysimilarity index 100%rename from browser_use/dom/__init__.pyrename to browser_use/dom/a11y/service.pydiff --git a/browser_use/dom/clickable_element_processor/service.py b/browser_use/dom/clickable_element_processor/service.pydeleted file mode 100644index dd2da869a..000000000--- a/browser_use/dom/clickable_element_processor/service.py+++ /dev/null@@ -1,70 +0,0 @@-import hashlib--from browser_use.dom.views import DOMElementNode---class ClickableElementProcessor:- @staticmethod- def get_clickable_elements_hashes(dom_element: DOMElementNode) -> set[str]:- """Get all clickable elements in the DOM tree"""- clickable_elements = ClickableElementProcessor.get_clickable_elements(dom_element)- return {ClickableElementProcessor.hash_dom_element(element) for element in clickable_elements}-- @staticmethod- def get_clickable_elements(dom_element: DOMElementNode) -> list[DOMElementNode]:- """Get all clickable elements in the DOM tree"""- clickable_elements = list()- for child in dom_element.children:- if isinstance(child, DOMElementNode):- if child.highlight_index:- clickable_elements.append(child)-- clickable_elements.extend(ClickableElementProcessor.get_clickable_elements(child))-- return list(clickable_elements)-- @staticmethod- def hash_dom_element(dom_element: DOMElementNode) -> str:- parent_branch_path = ClickableElementProcessor._get_parent_branch_path(dom_element)- branch_path_hash = ClickableElementProcessor._parent_branch_path_hash(parent_branch_path)- attributes_hash = ClickableElementProcessor._attributes_hash(dom_element.attributes)- xpath_hash = ClickableElementProcessor._xpath_hash(dom_element.xpath)- # text_hash = DomTreeProcessor._text_hash(dom_element)-- return ClickableElementProcessor._hash_string(f'{branch_path_hash}-{attributes_hash}-{xpath_hash}')-- @staticmethod- def _get_parent_branch_path(dom_element: DOMElementNode) -> list[str]:- parents: list[DOMElementNode] = []- current_element: DOMElementNode = dom_element- while current_element.parent is not None:- parents.append(current_element)- current_element = current_element.parent-- parents.reverse()-- return [parent.tag_name for parent in parents]-- @staticmethod- def _parent_branch_path_hash(parent_branch_path: list[str]) -> str:- parent_branch_path_string = '/'.join(parent_branch_path)- return hashlib.sha256(parent_branch_path_string.encode()).hexdigest()-- @staticmethod- def _attributes_hash(attributes: dict[str, str]) -> str:- attributes_string = ''.join(f'{key}={value}' for key, value in attributes.items())- return ClickableElementProcessor._hash_string(attributes_string)-- @staticmethod- def _xpath_hash(xpath: str) -> str:- return ClickableElementProcessor._hash_string(xpath)-- @staticmethod- def _text_hash(dom_element: DOMElementNode) -> str:- """ """- text_string = dom_element.get_all_text_till_next_clickable_element()- return ClickableElementProcessor._hash_string(text_string)-- @staticmethod- def _hash_string(string: str) -> str:- return hashlib.sha256(string.encode()).hexdigest()diff --git a/browser_use/dom/dom_tree/index.js b/browser_use/dom/dom_tree/index.jsdeleted file mode 100644index f1b161e5f..000000000--- a/browser_use/dom/dom_tree/index.js+++ /dev/null@@ -1,1381 +0,0 @@-(- args = {- doHighlightElements: true,- focusHighlightIndex: -1,- viewportExpansion: 0,- debugMode: false,- }-) => {- const { doHighlightElements, focusHighlightIndex, viewportExpansion, debugMode } = args;- let highlightIndex = 0; // Reset highlight index-- // Add caching mechanisms at the top level- const DOM_CACHE = {- boundingRects: new WeakMap(),- clientRects: new WeakMap(),- computedStyles: new WeakMap(),- clearCache: () => {- DOM_CACHE.boundingRects = new WeakMap();- DOM_CACHE.clientRects = new WeakMap();- DOM_CACHE.computedStyles = new WeakMap();- }- };-- /**- * Gets the cached bounding rect for an element.- *- * @param {HTMLElement} element - The element to get the bounding rect for.- * @returns {DOMRect | null} The cached bounding rect, or null if the element is not found.- */- function getCachedBoundingRect(element) {- if (!element) return null;-- if (DOM_CACHE.boundingRects.has(element)) {- return DOM_CACHE.boundingRects.get(element);- }-- const rect = element.getBoundingClientRect();-- if (rect) {- DOM_CACHE.boundingRects.set(element, rect);- }- return rect;- }-- /**- * Gets the cached computed style for an element.- *- * @param {HTMLElement} element - The element to get the computed style for.- * @returns {CSSStyleDeclaration | null} The cached computed style, or null if the element is not found.- */- function getCachedComputedStyle(element) {- if (!element) return null;-- if (DOM_CACHE.computedStyles.has(element)) {- return DOM_CACHE.computedStyles.get(element);- }-- const style = window.getComputedStyle(element);-- if (style) {- DOM_CACHE.computedStyles.set(element, style);- }- return style;- }-- /**- * Gets the cached client rects for an element.- *- * @param {HTMLElement} element - The element to get the client rects for.- * @returns {DOMRectList | null} The cached client rects, or null if the element is not found.- */- function getCachedClientRects(element) {- if (!element) return null;-- if (DOM_CACHE.clientRects.has(element)) {- return DOM_CACHE.clientRects.get(element);- }-- const rects = element.getClientRects();-- if (rects) {- DOM_CACHE.clientRects.set(element, rects);- }- return rects;- }-- /**- * Hash map of DOM nodes indexed by their highlight index.- *- * @type {Object<string, any>}- */- const DOM_HASH_MAP = {};-- const ID = { current: 0 };-- const HIGHLIGHT_CONTAINER_ID = "playwright-highlight-container";-- // Add a WeakMap cache for XPath strings- const xpathCache = new WeakMap();-- // // Initialize once and reuse- // const viewportObserver = new IntersectionObserver(- // (entries) => {- // entries.forEach(entry => {- // elementVisibilityMap.set(entry.target, entry.isIntersecting);- // });- // },- // { rootMargin: `${viewportExpansion}px` }- // );-- /**- * Highlights an element in the DOM and returns the index of the next element.- *- * @param {HTMLElement} element - The element to highlight.- * @param {number} index - The index of the element.- * @param {HTMLElement | null} parentIframe - The parent iframe node.- * @returns {number} The index of the next element.- */- function highlightElement(element, index, parentIframe = null) {- if (!element) return index;-- const overlays = [];- /**- * @type {HTMLElement | null}- */- let label = null;- let labelWidth = 20;- let labelHeight = 16;- let cleanupFn = null;-- try {- // Create or get highlight container- let container = document.getElementById(HIGHLIGHT_CONTAINER_ID);- if (!container) {- container = document.createElement("div");- container.id = HIGHLIGHT_CONTAINER_ID;- container.style.position = "fixed";- container.style.pointerEvents = "none";- container.style.top = "0";- container.style.left = "0";- container.style.width = "100%";- container.style.height = "100%";- // Use the maximum valid value in zIndex to ensure the element is not blocked by overlapping elements.- container.style.zIndex = "2147483647";- container.style.backgroundColor = 'transparent';- document.body.appendChild(container);- }-- // Get element client rects- const rects = element.getClientRects(); // Use getClientRects()-- if (!rects || rects.length === 0) return index; // Exit if no rects-- // Generate a color based on the index- const colors = [- "#FF0000",- "#00FF00",- "#0000FF",- "#FFA500",- "#800080",- "#008080",- "#FF69B4",- "#4B0082",- "#FF4500",- "#2E8B57",- "#DC143C",- "#4682B4",- ];- const colorIndex = index % colors.length;- const baseColor = colors[colorIndex];- const backgroundColor = baseColor + "1A"; // 10% opacity version of the color-- // Get iframe offset if necessary- let iframeOffset = { x: 0, y: 0 };- if (parentIframe) {- const iframeRect = parentIframe.getBoundingClientRect(); // Keep getBoundingClientRect for iframe offset- iframeOffset.x = iframeRect.left;- iframeOffset.y = iframeRect.top;- }-- // Create fragment to hold overlay elements- const fragment = document.createDocumentFragment();-- // Create highlight overlays for each client rect- for (const rect of rects) {- if (rect.width === 0 || rect.height === 0) continue; // Skip empty rects-- const overlay = document.createElement("div");- overlay.style.position = "fixed";- overlay.style.border = `2px solid ${baseColor}`;- overlay.style.backgroundColor = backgroundColor;- overlay.style.pointerEvents = "none";- overlay.style.boxSizing = "border-box";-- const top = rect.top + iframeOffset.y;- const left = rect.left + iframeOffset.x;-- overlay.style.top = `${top}px`;- overlay.style.left = `${left}px`;- overlay.style.width = `${rect.width}px`;- overlay.style.height = `${rect.height}px`;-- fragment.appendChild(overlay);- overlays.push({ element: overlay, initialRect: rect }); // Store overlay and its rect- }-- // Create and position a single label relative to the first rect- const firstRect = rects[0];- label = document.createElement("div");- label.className = "playwright-highlight-label";- label.style.position = "fixed";- label.style.background = baseColor;- label.style.color = "white";- label.style.padding = "1px 4px";- label.style.borderRadius = "4px";- label.style.fontSize = `${Math.min(12, Math.max(8, firstRect.height / 2))}px`;- label.textContent = index.toString();-- labelWidth = label.offsetWidth > 0 ? label.offsetWidth : labelWidth; // Update actual width if possible- labelHeight = label.offsetHeight > 0 ? label.offsetHeight : labelHeight; // Update actual height if possible-- const firstRectTop = firstRect.top + iframeOffset.y;- const firstRectLeft = firstRect.left + iframeOffset.x;-- let labelTop = firstRectTop + 2;- let labelLeft = firstRectLeft + firstRect.width - labelWidth - 2;-- // Adjust label position if first rect is too small- if (firstRect.width < labelWidth + 4 || firstRect.height < labelHeight + 4) {- labelTop = firstRectTop - labelHeight - 2;- labelLeft = firstRectLeft + firstRect.width - labelWidth; // Align with right edge- if (labelLeft < iframeOffset.x) labelLeft = firstRectLeft; // Prevent going off-left- }-- // Ensure label stays within viewport bounds slightly better- labelTop = Math.max(0, Math.min(labelTop, window.innerHeight - labelHeight));- labelLeft = Math.max(0, Math.min(labelLeft, window.innerWidth - labelWidth));--- label.style.top = `${labelTop}px`;- label.style.left = `${labelLeft}px`;-- fragment.appendChild(label);-- // Update positions on scroll/resize- const updatePositions = () => {- const newRects = element.getClientRects(); // Get fresh rects- let newIframeOffset = { x: 0, y: 0 };-- if (parentIframe) {- const iframeRect = parentIframe.getBoundingClientRect(); // Keep getBoundingClientRect for iframe- newIframeOffset.x = iframeRect.left;- newIframeOffset.y = iframeRect.top;- }-- // Update each overlay- overlays.forEach((overlayData, i) => {- if (i < newRects.length) { // Check if rect still exists- const newRect = newRects[i];- const newTop = newRect.top + newIframeOffset.y;- const newLeft = newRect.left + newIframeOffset.x;-- overlayData.element.style.top = `${newTop}px`;- overlayData.element.style.left = `${newLeft}px`;- overlayData.element.style.width = `${newRect.width}px`;- overlayData.element.style.height = `${newRect.height}px`;- overlayData.element.style.display = (newRect.width === 0 || newRect.height === 0) ? 'none' : 'block';- } else {- // If fewer rects now, hide extra overlays- overlayData.element.style.display = 'none';- }- });-- // If there are fewer new rects than overlays, hide the extras- if (newRects.length < overlays.length) {- for (let i = newRects.length; i < overlays.length; i++) {- overlays[i].element.style.display = 'none';- }- }-- // Update label position based on the first new rect- if (label && newRects.length > 0) {- const firstNewRect = newRects[0];- const firstNewRectTop = firstNewRect.top + newIframeOffset.y;- const firstNewRectLeft = firstNewRect.left + newIframeOffset.x;-- let newLabelTop = firstNewRectTop + 2;- let newLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth - 2;-- if (firstNewRect.width < labelWidth + 4 || firstNewRect.height < labelHeight + 4) {- newLabelTop = firstNewRectTop - labelHeight - 2;- newLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth;- if (newLabelLeft < newIframeOffset.x) newLabelLeft = firstNewRectLeft;- }-- // Ensure label stays within viewport bounds- newLabelTop = Math.max(0, Math.min(newLabelTop, window.innerHeight - labelHeight));- newLabelLeft = Math.max(0, Math.min(newLabelLeft, window.innerWidth - labelWidth));-- label.style.top = `${newLabelTop}px`;- label.style.left = `${newLabelLeft}px`;- label.style.display = 'block';- } else if (label) {- // Hide label if element has no rects anymore- label.style.display = 'none';- }- };--- const throttleFunction = (func, delay) => {- let lastCall = 0;- return (...args) => {- const now = performance.now();- if (now - lastCall < delay) return;- lastCall = now;- return func(...args);- };- };-- const throttledUpdatePositions = throttleFunction(updatePositions, 16); // ~60fps- window.addEventListener('scroll', throttledUpdatePositions, true);- window.addEventListener('resize', throttledUpdatePositions);-- // Add cleanup function- cleanupFn = () => {- window.removeEventListener('scroll', throttledUpdatePositions, true);- window.removeEventListener('resize', throttledUpdatePositions);- // Remove overlay elements if needed- overlays.forEach(overlay => overlay.element.remove());- if (label) label.remove();- };-- // Then add fragment to container in one operation- container.appendChild(fragment);-- return index + 1;- } finally {- // Store cleanup function for later use- if (cleanupFn) {- // Keep a reference to cleanup functions in a global array- (window._highlightCleanupFunctions = window._highlightCleanupFunctions || []).push(cleanupFn);- }- }- }-- // // Add this function to perform cleanup when needed- // function cleanupHighlights() {- // if (window._highlightCleanupFunctions && window._highlightCleanupFunctions.length) {- // window._highlightCleanupFunctions.forEach(fn => fn());- // window._highlightCleanupFunctions = [];- // }-- // // Also remove the container- // const container = document.getElementById(HIGHLIGHT_CONTAINER_ID);- // if (container) container.remove();- // }-- /**- * Gets the position of an element in its parent.- *- * @param {HTMLElement} currentElement - The element to get the position for.- * @returns {number} The position of the element in its parent.- */- function getElementPosition(currentElement) {- if (!currentElement.parentElement) {- return 0; // No parent means no siblings- }-- const tagName = currentElement.nodeName.toLowerCase();-- const siblings = Array.from(currentElement.parentElement.children)- .filter((sib) => sib.nodeName.toLowerCase() === tagName);-- if (siblings.length === 1) {- return 0; // Only element of its type- }-- const index = siblings.indexOf(currentElement) + 1; // 1-based index- return index;- }--- function getXPathTree(element, stopAtBoundary = true) {- if (xpathCache.has(element)) return xpathCache.get(element);-- const segments = [];- let currentElement = element;-- while (currentElement && currentElement.nodeType === Node.ELEMENT_NODE) {- // Stop if we hit a shadow root or iframe- if (- stopAtBoundary &&- (currentElement.parentNode instanceof ShadowRoot ||- currentElement.parentNode instanceof HTMLIFrameElement)- ) {- break;- }-- const position = getElementPosition(currentElement);- const tagName = currentElement.nodeName.toLowerCase();- const xpathIndex = position > 0 ? `[${position}]` : "";- segments.unshift(`${tagName}${xpathIndex}`);-- currentElement = currentElement.parentNode;- }-- const result = segments.join("/");- xpathCache.set(element, result);- return result;- }-- /**- * Checks if a text node is visible.- *- * @param {Text} textNode - The text node to check.- * @returns {boolean} Whether the text node is visible.- */- function isTextNodeVisible(textNode) {- try {- // Special case: when viewportExpansion is -1, consider all text nodes as visible- if (viewportExpansion === -1) {- // Still check parent visibility for basic filtering- const parentElement = textNode.parentElement;- if (!parentElement) return false;-- try {- return parentElement.checkVisibility({- checkOpacity: true,- checkVisibilityCSS: true,- });- } catch (e) {- // Fallback if checkVisibility is not supported- const style = window.getComputedStyle(parentElement);- return style.display !== 'none' &&- style.visibility !== 'hidden' &&- style.opacity !== '0';- }- }-- const range = document.createRange();- range.selectNodeContents(textNode);- const rects = range.getClientRects(); // Use getClientRects for Range-- if (!rects || rects.length === 0) {- return false;- }-- let isAnyRectVisible = false;- let isAnyRectInViewport = false;-- for (const rect of rects) {- // Check size- if (rect.width > 0 && rect.height > 0) {- isAnyRectVisible = true;-- // Viewport check for this rect- if (!(- rect.bottom < -viewportExpansion ||- rect.top > window.innerHeight + viewportExpansion ||- rect.right < -viewportExpansion ||- rect.left > window.innerWidth + viewportExpansion- )) {- isAnyRectInViewport = true;- break; // Found a visible rect in viewport, no need to check others- }- }- }-- if (!isAnyRectVisible || !isAnyRectInViewport) {- return false;- }-- // Check parent visibility- const parentElement = textNode.parentElement;- if (!parentElement) return false;-- try {- return parentElement.checkVisibility({- checkOpacity: true,- checkVisibilityCSS: true,- });- } catch (e) {- // Fallback if checkVisibility is not supported- const style = window.getComputedStyle(parentElement);- return style.display !== 'none' &&- style.visibility !== 'hidden' &&- style.opacity !== '0';- }- } catch (e) {- console.warn('Error checking text node visibility:', e);- return false;- }- }-- /**- * Checks if an element is accepted.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is accepted.- */- function isElementAccepted(element) {- if (!element || !element.tagName) return false;-- // Always accept body and common container elements- const alwaysAccept = new Set([- "body", "div", "main", "article", "section", "nav", "header", "footer"- ]);- const tagName = element.tagName.toLowerCase();-- if (alwaysAccept.has(tagName)) return true;-- const leafElementDenyList = new Set([- "svg",- "script",- "style",- "link",- "meta",- "noscript",- "template",- ]);-- return !leafElementDenyList.has(tagName);- }-- /**- * Checks if an element is visible.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is visible.- */- function isElementVisible(element) {- const style = getCachedComputedStyle(element);- return (- element.offsetWidth > 0 &&- element.offsetHeight > 0 &&- style?.visibility !== "hidden" &&- style?.display !== "none"- );- }-- /**- * Checks if an element is interactive.- *- * lots of comments, and uncommented code - to show the logic of what we already tried- *- * One of the things we tried at the beginning was also to use event listeners, and other fancy class, style stuff -> what actually worked best was just combining most things with computed cursor style :)- *- * @param {HTMLElement} element - The element to check.- */- function isInteractiveElement(element) {- if (!element || element.nodeType !== Node.ELEMENT_NODE) {- return false;- }-- // Cache the tagName and style lookups- const tagName = element.tagName.toLowerCase();- const style = getCachedComputedStyle(element);-- // Define interactive cursors- const interactiveCursors = new Set([- 'pointer', // Link/clickable elements- 'move', // Movable elements- 'text', // Text selection- 'grab', // Grabbable elements- 'grabbing', // Currently grabbing- 'cell', // Table cell selection- 'copy', // Copy operation- 'alias', // Alias creation- 'all-scroll', // Scrollable content- 'col-resize', // Column resize- 'context-menu', // Context menu available- 'crosshair', // Precise selection- 'e-resize', // East resize- 'ew-resize', // East-west resize- 'help', // Help available- 'n-resize', // North resize- 'ne-resize', // Northeast resize- 'nesw-resize', // Northeast-southwest resize- 'ns-resize', // North-south resize- 'nw-resize', // Northwest resize- 'nwse-resize', // Northwest-southeast resize- 'row-resize', // Row resize- 's-resize', // South resize- 'se-resize', // Southeast resize- 'sw-resize', // Southwest resize- 'vertical-text', // Vertical text selection- 'w-resize', // West resize- 'zoom-in', // Zoom in- 'zoom-out' // Zoom out- ]);-- // Define non-interactive cursors- const nonInteractiveCursors = new Set([- 'not-allowed', // Action not allowed- 'no-drop', // Drop not allowed- 'wait', // Processing- 'progress', // In progress- 'initial', // Initial value- 'inherit' // Inherited value- //? Let's just include all potentially clickable elements that are not specifically blocked- // 'none', // No cursor- // 'default', // Default cursor- // 'auto', // Browser default- ]);-- /**- * Checks if an element has an interactive pointer.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element has an interactive pointer.- */- function doesElementHaveInteractivePointer(element) {- if (element.tagName.toLowerCase() === "html") return false;-- if (style?.cursor && interactiveCursors.has(style.cursor)) return true;-- return false;- }-- let isInteractiveCursor = doesElementHaveInteractivePointer(element);-- // Genius fix for almost all interactive elements- if (isInteractiveCursor) {- return true;- }-- const interactiveElements = new Set([- "a", // Links- "button", // Buttons- "input", // All input types (text, checkbox, radio, etc.)- "select", // Dropdown menus- "textarea", // Text areas- "details", // Expandable details- "summary", // Summary element (clickable part of details)- "label", // Form labels (often clickable)- "option", // Select options- "optgroup", // Option groups- "fieldset", // Form fieldsets (can be interactive with legend)- "legend", // Fieldset legends- ]);-- // Define explicit disable attributes and properties- const explicitDisableTags = new Set([- 'disabled', // Standard disabled attribute- // 'aria-disabled', // ARIA disabled state- 'readonly', // Read-only state- // 'aria-readonly', // ARIA read-only state- // 'aria-hidden', // Hidden from accessibility- // 'hidden', // Hidden attribute- // 'inert', // Inert attribute- // 'aria-inert', // ARIA inert state- // 'tabindex="-1"', // Removed from tab order- // 'aria-hidden="true"' // Hidden from screen readers- ]);-- // handle inputs, select, checkbox, radio, textarea, button and make sure they are not cursor style disabled/not-allowed- if (interactiveElements.has(tagName)) {- // Check for non-interactive cursor- if (style?.cursor && nonInteractiveCursors.has(style.cursor)) {- return false;- }-- // Check for explicit disable attributes- for (const disableTag of explicitDisableTags) {- if (element.hasAttribute(disableTag) ||- element.getAttribute(disableTag) === 'true' ||- element.getAttribute(disableTag) === '') {- return false;- }- }-- // Check for disabled property on form elements- if (element.disabled) {- return false;- }-- // Check for readonly property on form elements- if (element.readOnly) {- return false;- }-- // Check for inert property- if (element.inert) {- return false;- }-- return true;- }-- const role = element.getAttribute("role");- const ariaRole = element.getAttribute("aria-role");-- // Check for contenteditable attribute- if (element.getAttribute("contenteditable") === "true" || element.isContentEditable) {- return true;- }-- // Added enhancement to capture dropdown interactive elements- if (element.classList && (- element.classList.contains("button") ||- element.classList.contains('dropdown-toggle') ||- element.getAttribute('data-index') ||- element.getAttribute('data-toggle') === 'dropdown' ||- element.getAttribute('aria-haspopup') === 'true'- )) {- return true;- }--- const interactiveRoles = new Set([- 'button', // Directly clickable element- // 'link', // Clickable link- // 'menuitem', // Clickable menu item- 'menuitemradio', // Radio-style menu item (selectable)- 'menuitemcheckbox', // Checkbox-style menu item (toggleable)- 'radio', // Radio button (selectable)- 'checkbox', // Checkbox (toggleable)- 'tab', // Tab (clickable to switch content)- 'switch', // Toggle switch (clickable to change state)- 'slider', // Slider control (draggable)- 'spinbutton', // Number input with up/down controls- 'combobox', // Dropdown with text input- 'searchbox', // Search input field- 'textbox', // Text input field- // 'listbox', // Selectable list- 'option', // Selectable option in a list- 'scrollbar' // Scrollable control- ]);--- // Basic role/attribute checks- const hasInteractiveRole =- interactiveElements.has(tagName) ||- (role && interactiveRoles.has(role)) ||- (ariaRole && interactiveRoles.has(ariaRole));-- if (hasInteractiveRole) return true;--- // check whether element has event listeners by window.getEventListeners- try {- if (typeof getEventListeners === 'function') {- const listeners = getEventListeners(element);- const mouseEvents = ['click', 'mousedown', 'mouseup', 'dblclick'];- for (const eventType of mouseEvents) {- if (listeners[eventType] && listeners[eventType].length > 0) {- return true; // Found a mouse interaction listener- }- }- }-- const getEventListenersForNode = element?.ownerDocument?.defaultView?.getEventListenersForNode || window.getEventListenersForNode;- if (typeof getEventListenersForNode === 'function') {- const listeners = getEventListenersForNode(element);- const interactionEvents = ['click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'submit', 'change', 'input', 'focus', 'blur'];- for (const eventType of interactionEvents) {- for (const listener of listeners) {- if (listener.type === eventType) {- return true; // Found a common interaction listener- }- }- }- }- // Fallback: Check common event attributes if getEventListeners is not available (getEventListeners doesn't work in page.evaluate context)- const commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick'];- for (const attr of commonMouseAttrs) {- if (element.hasAttribute(attr) || typeof element[attr] === 'function') {- return true;- }- }- } catch (e) {- // console.warn(`Could not check event listeners for ${element.tagName}:`, e);- // If checking listeners fails, rely on other checks- }-- return false- }--- /**- * Checks if an element is the topmost element at its position.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is the topmost element at its position.- */- function isTopElement(element) {- // Special case: when viewportExpansion is -1, consider all elements as "top" elements- if (viewportExpansion === -1) {- return true;- }-- const rects = getCachedClientRects(element); // Replace element.getClientRects()-- if (!rects || rects.length === 0) {- return false; // No geometry, cannot be top- }-- let isAnyRectInViewport = false;- for (const rect of rects) {- // Use the same logic as isInExpandedViewport check- if (rect.width > 0 && rect.height > 0 && !( // Only check non-empty rects- rect.bottom < -viewportExpansion ||- rect.top > window.innerHeight + viewportExpansion ||- rect.right < -viewportExpansion ||- rect.left > window.innerWidth + viewportExpansion- )) {- isAnyRectInViewport = true;- break;- }- }-- if (!isAnyRectInViewport) {- return false; // All rects are outside the viewport area- }--- // Find the correct document context and root element- let doc = element.ownerDocument;-- // If we're in an iframe, elements are considered top by default- if (doc !== window.document) {- return true;- }-- // For shadow DOM, we need to check within its own root context- const shadowRoot = element.getRootNode();- if (shadowRoot instanceof ShadowRoot) {- const centerX = rects[Math.floor(rects.length / 2)].left + rects[Math.floor(rects.length / 2)].width / 2;- const centerY = rects[Math.floor(rects.length / 2)].top + rects[Math.floor(rects.length / 2)].height / 2;-- try {- const topEl = shadowRoot.elementFromPoint(centerX, centerY);- if (!topEl) return false;-- let current = topEl;- while (current && current !== shadowRoot) {- if (current === element) return true;- current = current.parentElement;- }- return false;- } catch (e) {- return true;- }- }-- // For elements in viewport, check if they're topmost- const centerX = rects[Math.floor(rects.length / 2)].left + rects[Math.floor(rects.length / 2)].width / 2;- const centerY = rects[Math.floor(rects.length / 2)].top + rects[Math.floor(rects.length / 2)].height / 2;-- try {- const topEl = document.elementFromPoint(centerX, centerY);- if (!topEl) return false;-- let current = topEl;- while (current && current !== document.documentElement) {- if (current === element) return true;- current = current.parentElement;- }- return false;- } catch (e) {- return true;- }- }-- /**- * Checks if an element is within the expanded viewport.- *- * @param {HTMLElement} element - The element to check.- * @param {number} viewportExpansion - The viewport expansion.- * @returns {boolean} Whether the element is within the expanded viewport.- */- function isInExpandedViewport(element, viewportExpansion) {- if (viewportExpansion === -1) {- return true;- }-- const rects = element.getClientRects(); // Use getClientRects-- if (!rects || rects.length === 0) {- // Fallback to getBoundingClientRect if getClientRects is empty,- // useful for elements like <svg> that might not have client rects but have a bounding box.- const boundingRect = getCachedBoundingRect(element);- if (!boundingRect || boundingRect.width === 0 || boundingRect.height === 0) {- return false;- }- return !(- boundingRect.bottom < -viewportExpansion ||- boundingRect.top > window.innerHeight + viewportExpansion ||- boundingRect.right < -viewportExpansion ||- boundingRect.left > window.innerWidth + viewportExpansion- );- }-- // Check if *any* client rect is within the viewport- for (const rect of rects) {- if (rect.width === 0 || rect.height === 0) continue; // Skip empty rects-- if (!(- rect.bottom < -viewportExpansion ||- rect.top > window.innerHeight + viewportExpansion ||- rect.right < -viewportExpansion ||- rect.left > window.innerWidth + viewportExpansion- )) {- return true; // Found at least one rect in the viewport- }- }-- return false; // No rects were found in the viewport- }-- // /**- // * Gets the effective scroll of an element.- // *- // * @param {HTMLElement} element - The element to get the effective scroll for.- // * @returns {Object} The effective scroll of the element.- // */- // function getEffectiveScroll(element) {- // let currentEl = element;- // let scrollX = 0;- // let scrollY = 0;-- // while (currentEl && currentEl !== document.documentElement) {- // if (currentEl.scrollLeft || currentEl.scrollTop) {- // scrollX += currentEl.scrollLeft;- // scrollY += currentEl.scrollTop;- // }- // currentEl = currentEl.parentElement;- // }-- // scrollX += window.scrollX;- // scrollY += window.scrollY;-- // return { scrollX, scrollY };- // }-- /**- * Checks if an element is an interactive candidate.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is an interactive candidate.- */- function isInteractiveCandidate(element) {- if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;-- const tagName = element.tagName.toLowerCase();-- // Fast-path for common interactive elements- const interactiveElements = new Set([- "a", "button", "input", "select", "textarea", "details", "summary", "label"- ]);-- if (interactiveElements.has(tagName)) return true;-- // Quick attribute checks without getting full lists- const hasQuickInteractiveAttr = element.hasAttribute("onclick") ||- element.hasAttribute("role") ||- element.hasAttribute("tabindex") ||- element.hasAttribute("aria-") ||- element.hasAttribute("data-action") ||- element.getAttribute("contenteditable") === "true";-- return hasQuickInteractiveAttr;- }-- // --- Define constants for distinct interaction check ---- const DISTINCT_INTERACTIVE_TAGS = new Set([- 'a', 'button', 'input', 'select', 'textarea', 'summary', 'details', 'label', 'option'- ]);- const INTERACTIVE_ROLES = new Set([- 'button', 'link', 'menuitem', 'menuitemradio', 'menuitemcheckbox',- 'radio', 'checkbox', 'tab', 'switch', 'slider', 'spinbutton',- 'combobox', 'searchbox', 'textbox', 'listbox', 'option', 'scrollbar'- ]);--- /**- * Heuristically determines if an element should be considered as independently interactive,- * even if it's nested inside another interactive container.- *- * This function helps detect deeply nested actionable elements (e.g., menu items within a button)- * that may not be picked up by strict interactivity checks.- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is heuristically interactive.- */- function isHeuristicallyInteractive(element) {- if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;-- // Skip non-visible elements early for performance- if (!isElementVisible(element)) return false;-- // Check for common attributes that often indicate interactivity- const hasInteractiveAttributes =- element.hasAttribute('role') ||- element.hasAttribute('tabindex') ||- element.hasAttribute('onclick') ||- typeof element.onclick === 'function';-- // Check for semantic class names suggesting interactivity- const hasInteractiveClass = /\b(btn|clickable|menu|item|entry|link)\b/i.test(element.className || '');-- // Determine whether the element is inside a known interactive container- const isInKnownContainer = Boolean(- element.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar')- );-- // Ensure the element has at least one visible child (to avoid marking empty wrappers)- const hasVisibleChildren = [...element.children].some(isElementVisible);-- // Avoid highlighting elements whose parent is <body> (top-level wrappers)- const isParentBody = element.parentElement && element.parentElement.isSameNode(document.body);-- return (- (isInteractiveElement(element) || hasInteractiveAttributes || hasInteractiveClass) &&- hasVisibleChildren &&- isInKnownContainer &&- !isParentBody- );- }--- /**- * Checks if an element likely represents a distinct interaction- * separate from its parent (if the parent is also interactive).- *- * @param {HTMLElement} element - The element to check.- * @returns {boolean} Whether the element is a distinct interaction.- */- function isElementDistinctInteraction(element) {- if (!element || element.nodeType !== Node.ELEMENT_NODE) {- return false;- }-- const tagName = element.tagName.toLowerCase();- const role = element.getAttribute('role');-- // Check if it's an iframe - always distinct boundary- if (tagName === 'iframe') {- return true;- }-- // Check tag name- if (DISTINCT_INTERACTIVE_TAGS.has(tagName)) {- return true;- }- // Check interactive roles- if (role && INTERACTIVE_ROLES.has(role)) {- return true;- }- // Check contenteditable- if (element.isContentEditable || element.getAttribute('contenteditable') === 'true') {- return true;- }- // Check for common testing/automation attributes- if (element.hasAttribute('data-testid') || element.hasAttribute('data-cy') || element.hasAttribute('data-test')) {- return true;- }- // Check for explicit onclick handler (attribute or property)- if (element.hasAttribute('onclick') || typeof element.onclick === 'function') {- return true;- }-- // return false-- // Check for other common interaction event listeners- try {- const getEventListenersForNode = element?.ownerDocument?.defaultView?.getEventListenersForNode || window.getEventListenersForNode;- if (typeof getEventListenersForNode === 'function') {- const listeners = getEventListenersForNode(element);- const interactionEvents = ['click', 'mousedown', 'mouseup', 'keydown', 'keyup', 'submit', 'change', 'input', 'focus', 'blur'];- for (const eventType of interactionEvents) {- for (const listener of listeners) {- if (listener.type === eventType) {- return true; // Found a common interaction listener- }- }- }- }- // Fallback: Check common event attributes if getEventListeners is not available (getEventListenersForNode doesn't work in page.evaluate context)- const commonEventAttrs = ['onmousedown', 'onmouseup', 'onkeydown', 'onkeyup', 'onsubmit', 'onchange', 'oninput', 'onfocus', 'onblur'];- if (commonEventAttrs.some(attr => element.hasAttribute(attr))) {- return true;- }- } catch (e) {- // console.warn(`Could not check event listeners for ${element.tagName}:`, e);- // If checking listeners fails, rely on other checks- }---- // if the element is not strictly interactive but appears clickable based on heuristic signals- if (isHeuristicallyInteractive(element)) {- return true;- }-- // Default to false: if it's interactive but doesn't match above,- // assume it triggers the same action as the parent.- return false;- }- // --- End distinct interaction check ----- /**- * Handles the logic for deciding whether to highlight an element and performing the highlight.- * @param {- {- tagName: string;- attributes: Record<string, string>;- xpath: any;- children: never[];- isVisible?: boolean;- isTopElement?: boolean;- isInteractive?: boolean;- isInViewport?: boolean;- highlightIndex?: number;- shadowRoot?: boolean;- }} nodeData - The node data object.- * @param {HTMLElement} node - The node to highlight.- * @param {HTMLElement | null} parentIframe - The parent iframe node.- * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.- * @returns {boolean} Whether the element was highlighted.- */- function handleHighlighting(nodeData, node, parentIframe, isParentHighlighted) {- if (!nodeData.isInteractive) return false; // Not interactive, definitely don't highlight-- let shouldHighlight = false;- if (!isParentHighlighted) {- // Parent wasn't highlighted, this interactive node can be highlighted.- shouldHighlight = true;- } else {- // Parent *was* highlighted. Only highlight this node if it represents a distinct interaction.- if (isElementDistinctInteraction(node)) {- shouldHighlight = true;- } else {- // console.log(`Skipping highlight for ${nodeData.tagName} (parent highlighted)`);- shouldHighlight = false;- }- }-- if (shouldHighlight) {- // Check viewport status before assigning index and highlighting- nodeData.isInViewport = isInExpandedViewport(node, viewportExpansion);-- // When viewportExpansion is -1, all interactive elements should get a highlight index- // regardless of viewport status- if (nodeData.isInViewport || viewportExpansion === -1) {- nodeData.highlightIndex = highlightIndex++;-- if (doHighlightElements) {- if (focusHighlightIndex >= 0) {- if (focusHighlightIndex === nodeData.highlightIndex) {- highlightElement(node, nodeData.highlightIndex, parentIframe);- }- } else {- highlightElement(node, nodeData.highlightIndex, parentIframe);- }- return true; // Successfully highlighted- }- } else {- // console.log(`Skipping highlight for ${nodeData.tagName} (outside viewport)`);- }- }-- return false; // Did not highlight- }-- /**- * Creates a node data object for a given node and its descendants.- *- * @param {HTMLElement} node - The node to process.- * @param {HTMLElement | null} parentIframe - The parent iframe node.- * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.- * @returns {string | null} The ID of the node data object, or null if the node is not processed.- */- function buildDomTree(node, parentIframe = null, isParentHighlighted = false) {- // Fast rejection checks first- if (!node || node.id === HIGHLIGHT_CONTAINER_ID ||- (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)) {- return null;- }-- if (!node || node.id === HIGHLIGHT_CONTAINER_ID) {- return null;- }-- // Special handling for root node (body)- if (node === document.body) {- const nodeData = {- tagName: 'body',- attributes: {},- xpath: '/body',- children: [],- };-- // Process children of body- for (const child of node.childNodes) {- const domElement = buildDomTree(child, parentIframe, false); // Body's children have no highlighted parent initially- if (domElement) nodeData.children.push(domElement);- }-- const id = `${ID.current++}`;- DOM_HASH_MAP[id] = nodeData;- return id;- }-- // Early bailout for non-element nodes except text- if (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) {- return null;- }-- // Process text nodes- if (node.nodeType === Node.TEXT_NODE) {- const textContent = node.textContent?.trim();- if (!textContent) {- return null;- }-- // Only check visibility for text nodes that might be visible- const parentElement = node.parentElement;- if (!parentElement || parentElement.tagName.toLowerCase() === 'script') {- return null;- }-- const id = `${ID.current++}`;- DOM_HASH_MAP[id] = {- type: "TEXT_NODE",- text: textContent,- isVisible: isTextNodeVisible(node),- };- return id;- }-- // Quick checks for element nodes- if (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {- return null;- }-- // Early viewport check - only filter out elements clearly outside viewport- // The getBoundingClientRect() of the Shadow DOM host element may return width/height = 0- if (viewportExpansion !== -1 && !node.shadowRoot) {- const rect = getCachedBoundingRect(node); // Keep for initial quick check- const style = getCachedComputedStyle(node);-- // Skip viewport check for fixed/sticky elements as they may appear anywhere- const isFixedOrSticky = style && (style.position === 'fixed' || style.position === 'sticky');-- // Check if element has actual dimensions using offsetWidth/Height (quick check)- const hasSize = node.offsetWidth > 0 || node.offsetHeight > 0;-- // Use getBoundingClientRect for the quick OUTSIDE check.- // isInExpandedViewport will do the more accurate check later if needed.- if (!rect || (!isFixedOrSticky && !hasSize && (- rect.bottom < -viewportExpansion ||- rect.top > window.innerHeight + viewportExpansion ||- rect.right < -viewportExpansion ||- rect.left > window.innerWidth + viewportExpansion- ))) {- // console.log("Skipping node outside viewport (quick check):", node.tagName, rect);- return null;- }- }-- /**- * @type {- {- tagName: string;- attributes: Record<string, string | null>;- xpath: any;- children: never[];- isVisible?: boolean;- isTopElement?: boolean;- isInteractive?: boolean;- isInViewport?: boolean;- highlightIndex?: number;- shadowRoot?: boolean;- }- } nodeData - The node data object.- */- const nodeData = {- tagName: node.tagName.toLowerCase(),- attributes: {},- xpath: getXPathTree(node, true),- children: [],- };-- // Get attributes for interactive elements or potential text containers- if (isInteractiveCandidate(node) || node.tagName.toLowerCase() === 'iframe' || node.tagName.toLowerCase() === 'body') {- const attributeNames = node.getAttributeNames?.() || [];- for (const name of attributeNames) {- const value = node.getAttribute(name);- nodeData.attributes[name] = value;- }- }-- let nodeWasHighlighted = false;- // Perform visibility, interactivity, and highlighting checks- if (node.nodeType === Node.ELEMENT_NODE) {- nodeData.isVisible = isElementVisible(node); // isElementVisible uses offsetWidth/Height, which is fine- if (nodeData.isVisible) {- nodeData.isTopElement = isTopElement(node);- if (nodeData.isTopElement) {- nodeData.isInteractive = isInteractiveElement(node);- // Call the dedicated highlighting function- nodeWasHighlighted = handleHighlighting(nodeData, node, parentIframe, isParentHighlighted);- }- }- }-- // Process children, with special handling for iframes and rich text editors- if (node.tagName) {- const tagName = node.tagName.toLowerCase();-- // Handle iframes- if (tagName === "iframe") {- try {- const iframeDoc = node.contentDocument || node.contentWindow?.document;- if (iframeDoc) {- for (const child of iframeDoc.childNodes) {- const domElement = buildDomTree(child, node, false);- if (domElement) nodeData.children.push(domElement);- }- }- } catch (e) {- console.warn("Unable to access iframe:", e);- }- }- // Handle rich text editors and contenteditable elements- else if (- node.isContentEditable ||- node.getAttribute("contenteditable") === "true" ||- node.id === "tinymce" ||- node.classList.contains("mce-content-body") ||- (tagName === "body" && node.getAttribute("data-id")?.startsWith("mce_"))- ) {- // Process all child nodes to capture formatted text- for (const child of node.childNodes) {- const domElement = buildDomTree(child, parentIframe, nodeWasHighlighted);- if (domElement) nodeData.children.push(domElement);- }- }- else {- // Handle shadow DOM- if (node.shadowRoot) {- nodeData.shadowRoot = true;- for (const child of node.shadowRoot.childNodes) {- const domElement = buildDomTree(child, parentIframe, nodeWasHighlighted);- if (domElement) nodeData.children.push(domElement);- }- }- // Handle regular elements- for (const child of node.childNodes) {- // Pass the highlighted status of the *current* node to its children- const passHighlightStatusToChild = nodeWasHighlighted || isParentHighlighted;- const domElement = buildDomTree(child, parentIframe, passHighlightStatusToChild);- if (domElement) nodeData.children.push(domElement);- }- }- }-- // Skip empty anchor tags only if they have no dimensions and no children- if (nodeData.tagName === 'a' && nodeData.children.length === 0 && !nodeData.attributes.href) {- // Check if the anchor has actual dimensions- const rect = getCachedBoundingRect(node);- const hasSize = (rect && rect.width > 0 && rect.height > 0) || (node.offsetWidth > 0 || node.offsetHeight > 0);-- if (!hasSize) {- return null;- }- }-- const id = `${ID.current++}`;- DOM_HASH_MAP[id] = nodeData;- return id;- }-- const rootId = buildDomTree(document.body);-- // Clear the cache before starting- DOM_CACHE.clearCache();-- return { rootId, map: DOM_HASH_MAP };-};diff --git a/browser_use/dom/history_tree_processor/service.py b/browser_use/dom/history_tree_processor/service.pydeleted file mode 100644index 816b2fdd0..000000000--- a/browser_use/dom/history_tree_processor/service.py+++ /dev/null@@ -1,106 +0,0 @@-import hashlib--from browser_use.dom.history_tree_processor.view import DOMHistoryElement, HashedDomElement-from browser_use.dom.views import DOMElementNode---class HistoryTreeProcessor:- """ "- Operations on the DOM elements-- @dev be careful - text nodes can change even if elements stay the same- """-- @staticmethod- def convert_dom_element_to_history_element(dom_element: DOMElementNode) -> DOMHistoryElement:- from browser_use.browser.context import BrowserContext-- parent_branch_path = HistoryTreeProcessor._get_parent_branch_path(dom_element)- css_selector = BrowserContext._enhanced_css_selector_for_element(dom_element)- return DOMHistoryElement(- dom_element.tag_name,- dom_element.xpath,- dom_element.highlight_index,- parent_branch_path,- dom_element.attributes,- dom_element.shadow_root,- css_selector=css_selector,- page_coordinates=dom_element.page_coordinates,- viewport_coordinates=dom_element.viewport_coordinates,- viewport_info=dom_element.viewport_info,- )-- @staticmethod- def find_history_element_in_tree(dom_history_element: DOMHistoryElement, tree: DOMElementNode) -> DOMElementNode | None:- hashed_dom_history_element = HistoryTreeProcessor._hash_dom_history_element(dom_history_element)-- def process_node(node: DOMElementNode):- if node.highlight_index is not None:- hashed_node = HistoryTreeProcessor._hash_dom_element(node)- if hashed_node == hashed_dom_history_element:- return node- for child in node.children:- if isinstance(child, DOMElementNode):- result = process_node(child)- if result is not None:- return result- return None-- return process_node(tree)-- @staticmethod- def compare_history_element_and_dom_element(dom_history_element: DOMHistoryElement, dom_element: DOMElementNode) -> bool:- hashed_dom_history_element = HistoryTreeProcessor._hash_dom_history_element(dom_history_element)- hashed_dom_element = HistoryTreeProcessor._hash_dom_element(dom_element)-- return hashed_dom_history_element == hashed_dom_element-- @staticmethod- def _hash_dom_history_element(dom_history_element: DOMHistoryElement) -> HashedDomElement:- branch_path_hash = HistoryTreeProcessor._parent_branch_path_hash(dom_history_element.entire_parent_branch_path)- attributes_hash = HistoryTreeProcessor._attributes_hash(dom_history_element.attributes)- xpath_hash = HistoryTreeProcessor._xpath_hash(dom_history_element.xpath)-- return HashedDomElement(branch_path_hash, attributes_hash, xpath_hash)-- @staticmethod- def _hash_dom_element(dom_element: DOMElementNode) -> HashedDomElement:- parent_branch_path = HistoryTreeProcessor._get_parent_branch_path(dom_element)- branch_path_hash = HistoryTreeProcessor._parent_branch_path_hash(parent_branch_path)- attributes_hash = HistoryTreeProcessor._attributes_hash(dom_element.attributes)- xpath_hash = HistoryTreeProcessor._xpath_hash(dom_element.xpath)- # text_hash = DomTreeProcessor._text_hash(dom_element)-- return HashedDomElement(branch_path_hash, attributes_hash, xpath_hash)-- @staticmethod- def _get_parent_branch_path(dom_element: DOMElementNode) -> list[str]:- parents: list[DOMElementNode] = []- current_element: DOMElementNode = dom_element- while current_element.parent is not None:- parents.append(current_element)- current_element = current_element.parent-- parents.reverse()-- return [parent.tag_name for parent in parents]-- @staticmethod- def _parent_branch_path_hash(parent_branch_path: list[str]) -> str:- parent_branch_path_string = '/'.join(parent_branch_path)- return hashlib.sha256(parent_branch_path_string.encode()).hexdigest()-- @staticmethod- def _attributes_hash(attributes: dict[str, str]) -> str:- attributes_string = ''.join(f'{key}={value}' for key, value in attributes.items())- return hashlib.sha256(attributes_string.encode()).hexdigest()-- @staticmethod- def _xpath_hash(xpath: str) -> str:- return hashlib.sha256(xpath.encode()).hexdigest()-- @staticmethod- def _text_hash(dom_element: DOMElementNode) -> str:- """ """- text_string = dom_element.get_all_text_till_next_clickable_element()- return hashlib.sha256(text_string.encode()).hexdigest()diff --git a/browser_use/dom/history_tree_processor/view.py b/browser_use/dom/history_tree_processor/view.pydeleted file mode 100644index 32f01cd47..000000000--- a/browser_use/dom/history_tree_processor/view.py+++ /dev/null@@ -1,69 +0,0 @@-from dataclasses import dataclass--from pydantic import BaseModel---@dataclass-class HashedDomElement:- """- Hash of the dom element to be used as a unique identifier- """-- branch_path_hash: str- attributes_hash: str- xpath_hash: str- # text_hash: str---class Coordinates(BaseModel):- x: int- y: int---class CoordinateSet(BaseModel):- top_left: Coordinates- top_right: Coordinates- bottom_left: Coordinates- bottom_right: Coordinates- center: Coordinates- width: int- height: int---class ViewportInfo(BaseModel):- scroll_x: int | None = None- scroll_y: int | None = None- width: int- height: int---@dataclass-class DOMHistoryElement:- tag_name: str- xpath: str- highlight_index: int | None- entire_parent_branch_path: list[str]- attributes: dict[str, str]- shadow_root: bool = False- css_selector: str | None = None- page_coordinates: CoordinateSet | None = None- viewport_coordinates: CoordinateSet | None = None- viewport_info: ViewportInfo | None = None-- def to_dict(self) -> dict:- page_coordinates = self.page_coordinates.model_dump() if self.page_coordinates else None- viewport_coordinates = self.viewport_coordinates.model_dump() if self.viewport_coordinates else None- viewport_info = self.viewport_info.model_dump() if self.viewport_info else None-- return {- 'tag_name': self.tag_name,- 'xpath': self.xpath,- 'highlight_index': self.highlight_index,- 'entire_parent_branch_path': self.entire_parent_branch_path,- 'attributes': self.attributes,- 'shadow_root': self.shadow_root,- 'css_selector': self.css_selector,- 'page_coordinates': page_coordinates,- 'viewport_coordinates': viewport_coordinates,- 'viewport_info': viewport_info,- }diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.pydeleted file mode 100644index 2f3e2824e..000000000--- a/browser_use/dom/playground/extraction.py+++ /dev/null@@ -1,188 +0,0 @@-import asyncio-import json-import os-import time--import anyio-import pyperclip-import tiktoken--from browser_use.agent.prompts import AgentMessagePrompt-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.browser.types import ViewportSize-from browser_use.dom.service import DomService-from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES-from browser_use.filesystem.file_system import FileSystem--TIMEOUT = 60---async def test_focus_vs_all_elements():- # async with async_patchright() as patchright:- browser_session = 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,- ),- # playwright=patchright,- )-- websites = [- # 'https://demos.telerik.com/kendo-react-ui/treeview/overview/basic/func?theme=default-ocean-blue-a11y',- 'https://google.com',- 'https://www.ycombinator.com/companies',- 'https://kayak.com/flights',- # 'https://en.wikipedia.org/wiki/Humanist_Party_of_Ontario',- # 'https://www.google.com/travel/flights?tfs=CBwQARoJagcIARIDTEpVGglyBwgBEgNMSlVAAUgBcAGCAQsI____________AZgBAQ&tfu=KgIIAw&hl=en-US&gl=US',- # # 'https://www.concur.com/?&cookie_preferences=cpra',- # 'https://immobilienscout24.de',- 'https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit',- 'https://www.zeiss.com/career/en/job-search.html?page=1',- 'https://www.mlb.com/yankees/stats/',- 'https://www.amazon.com/s?k=laptop&s=review-rank&crid=1RZCEJ289EUSI&qid=1740202453&sprefix=laptop%2Caps%2C166&ref=sr_st_review-rank&ds=v1%3A4EnYKXVQA7DIE41qCvRZoNB4qN92Jlztd3BPsTFXmxU',- 'https://reddit.com',- 'https://codepen.io/geheimschriftstift/pen/mPLvQz',- 'https://www.google.com/search?q=google+hi&oq=google+hi&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRhA0gEIMjI2NmowajSoAgCwAgE&sourceid=chrome&ie=UTF-8',- 'https://amazon.com',- 'https://github.com',- ]-- await browser_session.start()- page = await browser_session.get_current_page()- dom_service = DomService(page)-- for website in websites:- # sleep 2- await page.goto(website)- await asyncio.sleep(1)-- last_clicked_index = None # Track the index for text input- while True:- try:- print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')-- # Get/refresh the state (includes removing old highlights)- print('\nGetting page state...')-- start_time = time.time()- all_elements_state = await browser_session.get_state_summary(True)- end_time = time.time()- print(f'get_state_summary took {end_time - start_time:.2f} seconds')-- selector_map = all_elements_state.selector_map- total_elements = len(selector_map.keys())- print(f'Total number of elements: {total_elements}')-- # print(all_elements_state.element_tree.clickable_elements_to_string())- prompt = AgentMessagePrompt(- browser_state_summary=all_elements_state,- file_system=FileSystem(base_dir='./tmp'),- include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,- step_info=None,- )- # Write the user message to a file for analysis- user_message = prompt.get_user_message(use_vision=False).text-- # clickable_elements_str = all_elements_state.element_tree.clickable_elements_to_string()-- text_to_save = user_message-- os.makedirs('./tmp', exist_ok=True)- async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:- await f.write(text_to_save)-- # save pure clickable elements to a file- async with await anyio.open_file('./tmp/element_tree.json', 'w', encoding='utf-8') as f:- await f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=0))-- # copy the user message to the clipboard- # pyperclip.copy(text_to_save)-- encoding = tiktoken.encoding_for_model('gpt-4o')- token_count = len(encoding.encode(text_to_save))- print(f'Token count: {token_count}')-- print('User message written to ./tmp/user_message.txt')- print('Element tree written to ./tmp/element_tree.json')-- # also save all_elements_state.element_tree.clickable_elements_to_string() to a file- # with open('./tmp/clickable_elements.json', 'w', encoding='utf-8') as f:- # f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))- # print('Clickable elements written to ./tmp/clickable_elements.json')-- answer = input(- "Enter element index to click, 'index,text' to input, 'c,index' to copy element JSON, or 'q' to quit: "- )-- if answer.lower() == 'q':- break-- try:- if answer.lower().startswith('c,'):- # Copy element JSON format: c,index- parts = answer.split(',', 1)- if len(parts) == 2:- try:- target_index = int(parts[1].strip())- if target_index in selector_map:- element_node = selector_map[target_index]- element_json = json.dumps(element_node.__json__(), indent=2, default=str)- pyperclip.copy(element_json)- print(f'Copied element {target_index} JSON to clipboard: {element_node.tag_name}')- else:- print(f'Invalid index: {target_index}')- except ValueError:- print(f'Invalid index format: {parts[1]}')- else:- print("Invalid input format. Use 'c,index'.")- elif ',' in answer:- # Input text format: index,text- parts = answer.split(',', 1)- if len(parts) == 2:- try:- target_index = int(parts[0].strip())- text_to_input = parts[1]- if target_index in selector_map:- element_node = selector_map[target_index]- print(- f"Inputting text '{text_to_input}' into element {target_index}: {element_node.tag_name}"- )- await browser_session._input_text_element_node(element_node, text_to_input)- print('Input successful.')- else:- print(f'Invalid index: {target_index}')- except ValueError:- print(f'Invalid index format: {parts[0]}')- else:- print("Invalid input format. Use 'index,text'.")- else:- # Click element format: index- try:- clicked_index = int(answer)- if clicked_index in selector_map:- element_node = selector_map[clicked_index]- print(f'Clicking element {clicked_index}: {element_node.tag_name}')- await browser_session._click_element_node(element_node)- print('Click successful.')- else:- print(f'Invalid index: {clicked_index}')- except ValueError:- print(f"Invalid input: '{answer}'. Enter an index, 'index,text', 'c,index', or 'q'.")-- except Exception as action_e:- print(f'Action failed: {action_e}')-- # No explicit highlight removal here, get_state handles it at the start of the loop-- except Exception as e:- print(f'Error in loop: {e}')- # Optionally add a small delay before retrying- await asyncio.sleep(1)---if __name__ == '__main__':- asyncio.run(test_focus_vs_all_elements())- # asyncio.run(test_process_html_file()) # Commented out the other testdiff --git a/browser_use/dom/playground/process_dom.py b/browser_use/dom/playground/process_dom.pydeleted file mode 100644index f7f1cf67f..000000000--- a/browser_use/dom/playground/process_dom.py+++ /dev/null@@ -1,45 +0,0 @@-import asyncio-import json-import os-import time--import anyio--from browser_use.browser import BrowserProfile, BrowserSession---async def test_process_dom():- browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True))- await browser_session.start()- try:- page = await browser_session.get_current_page()- await page.goto('https://kayak.com/flights')- # await page.goto('https://google.com/flights')- # await page.goto('https://immobilienscout24.de')- # await page.goto('https://seleniumbase.io/w3schools/iframes')-- await asyncio.sleep(3)-- async with await anyio.open_file('browser_use/dom/buildDomTree.js', 'r') as f:- js_code = await f.read()-- start = time.time()- dom_tree = await page.evaluate(js_code)- end = time.time()-- # print(dom_tree)- print(f'Time: {end - start:.2f}s')-- os.makedirs('./tmp', exist_ok=True)- async with await anyio.open_file('./tmp/dom.json', 'w') as f:- await f.write(json.dumps(dom_tree, indent=1))-- # both of these work for immobilienscout24.de- # await page.click('.sc-dcJsrY.ezjNCe')- # await page.click(- # 'div > div:nth-of-type(2) > div > div:nth-of-type(2) > div > div:nth-of-type(2) > div > div > div > button:nth-of-type(2)'- # )-- input('Press Enter to continue...')- finally:- await browser_session.stop()diff --git a/browser_use/dom/playground/test_accessibility.py b/browser_use/dom/playground/test_accessibility.pydeleted file mode 100644index 7db47fa7d..000000000--- a/browser_use/dom/playground/test_accessibility.py+++ /dev/null@@ -1,95 +0,0 @@-"""-Accessibility Tree Playground for browser-use--- Launches a browser and navigates to a target URL (default: amazon.com)-- Extracts both the full and interesting-only accessibility trees using Playwright-- Prints and saves both trees to JSON files-- Recursively prints relevant info for each node (role, name, value, description, focusable, focused, checked, selected, disabled, children count)-- Explains the difference between the accessibility tree and the DOM tree-- Notes on React/Vue/SPA apps-- Easy to modify for your own experiments--Run with: python browser_use/dom/tests/test_accessibility_playground.py-"""--import asyncio--from browser_use.browser.types import async_playwright--# Change this to any site you want to test---# Helper to recursively print relevant info from the accessibility tree-def print_ax_tree(node, depth=0):- if not node:- return- indent = ' ' * depth- info = [- f'role={node.get("role")!r}',- f'name={node.get("name")!r}' if node.get('name') else None,- f'value={node.get("value")!r}' if node.get('value') else None,- f'desc={node.get("description")!r}' if node.get('description') else None,- f'focusable={node.get("focusable")!r}' if 'focusable' in node else None,- f'focused={node.get("focused")!r}' if 'focused' in node else None,- f'checked={node.get("checked")!r}' if 'checked' in node else None,- f'selected={node.get("selected")!r}' if 'selected' in node else None,- f'disabled={node.get("disabled")!r}' if 'disabled' in node else None,- f'children={len(node.get("children", []))}' if node.get('children') else None,- ]- print('--------------------------------')- print(indent + ', '.join([x for x in info if x]))- for child in node.get('children', []):- print_ax_tree(child, depth + 1)---# Helper to print all available accessibility node attributes-# Prints all key-value pairs for each node (except 'children'), then recurses into children-def print_all_fields(node, depth=0):- if not node:- return- indent = ' ' * depth- for k, v in node.items():- if k != 'children':- print(f'{indent}{k}: {v!r}')- if 'children' in node:- print(f'{indent}children: {len(node["children"])}')- for child in node['children']:- print_all_fields(child, depth + 1)---def flatten_ax_tree(node, lines):- if not node:- return- role = node.get('role', '')- name = node.get('name', '')- lines.append(f'{role} {name}')- for child in node.get('children', []):- flatten_ax_tree(child, lines)---async def get_ax_tree(TARGET_URL):- async with async_playwright() as p:- browser = await p.chromium.launch(headless=True)- page = await browser.new_page()- print(f'Navigating to {TARGET_URL}')- await page.goto(TARGET_URL, wait_until='domcontentloaded')-- ax_tree_interesting = await page.accessibility.snapshot(interesting_only=True)- lines = []- flatten_ax_tree(ax_tree_interesting, lines)- print(lines)- print(f'length of ax_tree_interesting: {len(lines)}')-- await browser.close()---if __name__ == '__main__':- TARGET_URL = [- # 'https://amazon.com/',- # 'https://www.google.com/',- # 'https://www.facebook.com/',- # 'https://platform.openai.com/tokenizer',- 'https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/checkbox',- ]- for url in TARGET_URL:- asyncio.run(get_ax_tree(url))diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.pynew file mode 100644index 000000000..6de95048b--- /dev/null+++ b/browser_use/dom/playground/tree.py@@ -0,0 +1,49 @@+import asyncio+import json+import time++import aiofiles+import httpx+from playwright.async_api import async_playwright++from browser_use.browser import Browser+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 = Browser(browser=playwright_browser)++ async with httpx.AsyncClient() as client:+ version_info = await client.get('http://localhost:9222/json/version')+ browser.cdp_url = version_info.json()['webSocketDebuggerUrl']++ await browser.create_new_tab('https://en.wikipedia.org/wiki/Apple_Inc.')+ await browser._wait_for_page_and_frames_load()++ dom_service = DOMService(browser)++ start = time.time()+ snapshot, dom_tree, ax_tree = await dom_service.get_dom_tree()+ 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/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')++ print('Done')+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex dc059732a..50c2fae30 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -1,225 +1,74 @@-import logging-from importlib import resources-from typing import TYPE_CHECKING-from urllib.parse import urlparse--if TYPE_CHECKING:- from browser_use.browser.types import Page---from browser_use.dom.views import (- DOMBaseNode,- DOMElementNode,- DOMState,- DOMTextNode,- SelectorMap,- ViewportInfo,-)-from browser_use.utils import is_new_tab_page, time_execution_async--# @dataclass-# class ViewportInfo:-# width: int-# height: int---class DomService:- logger: logging.Logger-- def __init__(self, page: 'Page', logger: logging.Logger | None = None):- self.page = page- self.xpath_cache = {}- self.logger = logger or logging.getLogger(__name__)-- self.js_code = resources.files('browser_use.dom.dom_tree').joinpath('index.js').read_text()-- # region - Clickable elements- @time_execution_async('--get_clickable_elements')- async def get_clickable_elements(- self,- highlight_elements: bool = True,- focus_element: int = -1,- viewport_expansion: int = 0,- ) -> DOMState:- element_tree, selector_map = await self._build_dom_tree(highlight_elements, focus_element, viewport_expansion)- return DOMState(element_tree=element_tree, selector_map=selector_map)-- @time_execution_async('--get_cross_origin_iframes')- async def get_cross_origin_iframes(self) -> list[str]:- # invisible cross-origin iframes are used for ads and tracking, dont open those- hidden_frame_urls = await self.page.locator('iframe').filter(visible=False).evaluate_all('e => e.map(e => e.src)')-- is_ad_url = lambda url: any(- domain in urlparse(url).netloc for domain in ('doubleclick.net', 'adroll.com', 'googletagmanager.com')- )-- return [- frame.url- for frame in self.page.frames- if urlparse(frame.url).netloc # exclude data:urls and new tab pages- and urlparse(frame.url).netloc != urlparse(self.page.url).netloc # exclude same-origin iframes- and frame.url not in hidden_frame_urls # exclude hidden frames- and not is_ad_url(frame.url) # exclude most common ad network tracker frame URLs- ]-- @time_execution_async('--build_dom_tree')- async def _build_dom_tree(- self,- highlight_elements: bool,- focus_element: int,- viewport_expansion: int,- ) -> tuple[DOMElementNode, SelectorMap]:- if await self.page.evaluate('1+1') != 2:- raise ValueError('The page cannot evaluate javascript code properly')-- if is_new_tab_page(self.page.url):- # short-circuit if the page is a new empty tab for speed, no need to inject buildDomTree.js- return (- DOMElementNode(- tag_name='body',- xpath='',- attributes={},- children=[],- is_visible=False,- parent=None,- ),- {},- )-- # 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.- debug_mode = self.logger.getEffectiveLevel() == logging.DEBUG- args = {- 'doHighlightElements': highlight_elements,- 'focusHighlightIndex': focus_element,- 'viewportExpansion': viewport_expansion,- 'debugMode': debug_mode,- }-- try:- self.logger.debug(f'🔧 Starting JavaScript DOM analysis for {self.page.url[:50]}...')- eval_page: dict = await self.page.evaluate(self.js_code, args)- self.logger.debug('✅ JavaScript DOM analysis completed')- except Exception as e:- self.logger.error('Error evaluating JavaScript: %s', e)- raise-- # Only log performance metrics in debug mode- if debug_mode and 'perfMetrics' in eval_page:- perf = eval_page['perfMetrics']-- # Get key metrics for summary- total_nodes = perf.get('nodeMetrics', {}).get('totalNodes', 0)- # processed_nodes = perf.get('nodeMetrics', {}).get('processedNodes', 0)-- # Count interactive elements from the DOM map- interactive_count = 0- if 'map' in eval_page:- for node_data in eval_page['map'].values():- if isinstance(node_data, dict) and node_data.get('isInteractive'):- interactive_count += 1-- # Create concise summary- url_short = self.page.url[:50] + '...' if len(self.page.url) > 50 else self.page.url- self.logger.debug(- '🔎 Ran buildDOMTree.js interactive element detection on: %s interactive=%d/%d\n',- url_short,- interactive_count,- total_nodes,- # processed_nodes,- )-- self.logger.debug('🔄 Starting Python DOM tree construction...')- result = await self._construct_dom_tree(eval_page)- self.logger.debug('✅ Python DOM tree construction completed')- return result-- @time_execution_async('--construct_dom_tree')- async def _construct_dom_tree(- self,- eval_page: dict,- ) -> tuple[DOMElementNode, SelectorMap]:- js_node_map = eval_page['map']- js_root_id = eval_page['rootId']-- selector_map = {}- node_map = {}-- for id, node_data in js_node_map.items():- node, children_ids = self._parse_node(node_data)- if node is None:- continue-- node_map[id] = node-- if isinstance(node, DOMElementNode) and node.highlight_index is not None:- selector_map[node.highlight_index] = node-- # NOTE: We know that we are building the tree bottom up- # and all children are already processed.- if isinstance(node, DOMElementNode):- for child_id in children_ids:- if child_id not in node_map:- continue-- child_node = node_map[child_id]-- child_node.parent = node- node.children.append(child_node)-- html_to_dict = node_map[str(js_root_id)]-- del node_map- del js_node_map- del js_root_id-- if html_to_dict is None or not isinstance(html_to_dict, DOMElementNode):- raise ValueError('Failed to parse HTML to dictionary')-- return html_to_dict, selector_map-- def _parse_node(- self,- node_data: dict,- ) -> tuple[DOMBaseNode | None, list[int]]:- if not node_data:- return None, []-- # Process text nodes immediately- if node_data.get('type') == 'TEXT_NODE':- text_node = DOMTextNode(- text=node_data['text'],- is_visible=node_data['isVisible'],- parent=None,- )- return text_node, []-- # Process coordinates if they exist for element nodes-- viewport_info = None-- if 'viewport' in node_data:- viewport_info = ViewportInfo(- width=node_data['viewport']['width'],- height=node_data['viewport']['height'],- )-- 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),- is_in_viewport=node_data.get('isInViewport', False),- highlight_index=node_data.get('highlightIndex'),- shadow_root=node_data.get('shadowRoot', False),- parent=None,- viewport_info=viewport_info,- )-- children_ids = node_data.get('children', [])-- return element_node, children_ids+from cdp_use import CDPClient++from browser_use.browser import Browser+++class DOMService:+ def __init__(self, browser: Browser):+ self.browser = browser++ self.cdp_client: CDPClient | None = None+ self.playwright_page_to_session_id_store: dict[str, str] = {}++ async def _get_cdp_client(self) -> CDPClient:+ if self.cdp_client is None:+ if not self.browser.cdp_url:+ raise ValueError('CDP URL is not set')++ self.cdp_client = CDPClient(self.browser.cdp_url)+ await self.cdp_client.start()+ return self.cdp_client++ # on self destroy -> stop the cdp client+ async def __del__(self):+ if self.cdp_client:+ await self.cdp_client.stop()+ self.cdp_client = None++ async def _get_current_page_session_id(self) -> str:+ """Get the target ID for a playwright page.++ TODO: this is a REALLY hacky way -> if multiple same urls are open then this will break+ """+ page = await self.browser.get_current_page()+ page_guid = page._impl_obj._guid++ # if page_guid in self.page_to_session_id_store:+ # return self.page_to_session_id_store[page_guid]++ cdp_client = await self._get_cdp_client()++ targets = await cdp_client.send.Target.getTargets()+ for target in targets['targetInfos']:+ if target['type'] == 'page' and target['url'] == page.url:+ # cache the session id for this playwright page+ self.playwright_page_to_session_id_store[page_guid] = target['targetId']++ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target['targetId'], 'flatten': True})+ session_id = session['sessionId']++ await cdp_client.send.Target.setAutoAttach(+ params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}+ )++ await cdp_client.send.DOM.enable(session_id=session_id)+ await cdp_client.send.Accessibility.enable(session_id=session_id)++ return session_id++ raise ValueError(f'No session id found for page {page.url}')++ async def get_dom_tree(self):+ if not self.browser.cdp_url:+ raise ValueError('CDP URL is not set')++ session_id = await self._get_current_page_session_id()+ cdp_client = await self._get_cdp_client()++ snapshot = await cdp_client.send.DOMSnapshot.captureSnapshot(params={'computedStyles': []}, session_id=session_id)++ dom_tree = await cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)++ ax_tree = await cdp_client.send.Accessibility.getFullAXTree(session_id=session_id)++ return snapshot, dom_tree, ax_treediff --git a/browser_use/dom/utils.py b/browser_use/dom/utils.pydeleted file mode 100644index 0485a0ea0..000000000--- a/browser_use/dom/utils.py+++ /dev/null@@ -1,4 +0,0 @@-def cap_text_length(text: str, max_length: int) -> str:- if len(text) > max_length:- return text[:max_length] + '...'- return textdiff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 42cf3bb0b..937fbc632 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -1,57 +1,8 @@from dataclasses import dataclass-from functools import cached_property-from typing import TYPE_CHECKING, Optional--from browser_use.dom.history_tree_processor.view import CoordinateSet, HashedDomElement, ViewportInfo-from browser_use.dom.utils import cap_text_length-from browser_use.utils import time_execution_sync--# Avoid circular import issues-if TYPE_CHECKING:- from .views import DOMElementNode---@dataclass(frozen=False)-class DOMBaseNode:- is_visible: bool- # Use None as default and set parent later to avoid circular reference issues- parent: Optional['DOMElementNode']-- def __json__(self) -> dict:- raise NotImplementedError('DOMBaseNode is an abstract class')---@dataclass(frozen=False)-class DOMTextNode(DOMBaseNode):- text: str- type: str = 'TEXT_NODE'-- def has_parent_with_highlight_index(self) -> bool:- current = self.parent- while current is not None:- # stop if the element has a highlight index (will be handled separately)- if current.highlight_index is not None:- return True-- current = current.parent- return False-- def is_parent_in_viewport(self) -> bool:- if self.parent is None:- return False- return self.parent.is_in_viewport-- def is_parent_top_element(self) -> bool:- if self.parent is None:- return False- return self.parent.is_top_element-- def __json__(self) -> dict:- return {- 'text': self.text,- 'type': self.type,- }+from enum import Enum+from cdp_use.cdp.dom.types import ShadowRootType+from pydantic import BaseModelDEFAULT_INCLUDE_ATTRIBUTES = ['title',@@ -70,220 +21,89 @@ DEFAULT_INCLUDE_ATTRIBUTES = []-@dataclass(frozen=False)-class DOMElementNode(DOMBaseNode):- """- xpath: the xpath of the element from the last root node (shadow root or iframe OR document if no shadow root or iframe).- To properly reference the element we need to recursively switch the root node until we find the element (work you way up the tree with `.parent`)- """-- tag_name: str- xpath: str- attributes: dict[str, str]- children: list[DOMBaseNode]- is_interactive: bool = False- is_top_element: bool = False- is_in_viewport: bool = False- shadow_root: bool = False- highlight_index: int | None = None- viewport_coordinates: CoordinateSet | None = None- page_coordinates: CoordinateSet | None = None- viewport_info: ViewportInfo | None = None-- """- ### State injected by the browser context.-- The idea is that the clickable elements are sometimes persistent from the previous page -> tells the model which objects are new/_how_ the state has changed- """- is_new: bool | None = None-- def __json__(self) -> dict:- return {- 'tag_name': self.tag_name,- 'xpath': self.xpath,- 'attributes': self.attributes,- 'is_visible': self.is_visible,- 'is_interactive': self.is_interactive,- 'is_top_element': self.is_top_element,- 'is_in_viewport': self.is_in_viewport,- 'shadow_root': self.shadow_root,- 'highlight_index': self.highlight_index,- 'viewport_coordinates': self.viewport_coordinates,- 'page_coordinates': self.page_coordinates,- 'children': [child.__json__() for child in self.children],- }-- def __repr__(self) -> str:- tag_str = f'<{self.tag_name}'-- # Add attributes- for key, value in self.attributes.items():- tag_str += f' {key}="{value}"'- tag_str += '>'-- # Add extra info- extras = []- if self.is_interactive:- extras.append('interactive')- if self.is_top_element:- extras.append('top')- if self.shadow_root:- extras.append('shadow-root')- if self.highlight_index is not None:- extras.append(f'highlight:{self.highlight_index}')- if self.is_in_viewport:- extras.append('in-viewport')-- if extras:- tag_str += f' [{", ".join(extras)}]'-- return tag_str-- @cached_property- def hash(self) -> HashedDomElement:- from browser_use.dom.history_tree_processor.service import (- HistoryTreeProcessor,- )-- return HistoryTreeProcessor._hash_dom_element(self)+class NodeType(int, Enum):+ """DOM node types based on the DOM specification."""- def get_all_text_till_next_clickable_element(self, max_depth: int = -1) -> str:- text_parts = []+ ELEMENT_NODE = 1+ ATTRIBUTE_NODE = 2+ TEXT_NODE = 3+ CDATA_SECTION_NODE = 4+ ENTITY_REFERENCE_NODE = 5+ ENTITY_NODE = 6+ PROCESSING_INSTRUCTION_NODE = 7+ COMMENT_NODE = 8+ DOCUMENT_NODE = 9+ DOCUMENT_TYPE_NODE = 10+ DOCUMENT_FRAGMENT_NODE = 11+ NOTATION_NODE = 12- def collect_text(node: DOMBaseNode, current_depth: int) -> None:- if max_depth != -1 and current_depth > max_depth:- return- # Skip this branch if we hit a highlighted element (except for the current node)- if isinstance(node, DOMElementNode) and node != self and node.highlight_index is not None:- return+class DOMNodeAttributes(BaseModel):+ name: str+ value: str- if isinstance(node, DOMTextNode):- text_parts.append(node.text)- elif isinstance(node, DOMElementNode):- for child in node.children:- collect_text(child, current_depth + 1)- collect_text(self, 0)- return '\n'.join(text_parts).strip()-- @time_execution_sync('--clickable_elements_to_string')- def clickable_elements_to_string(self, include_attributes: list[str] | None = None) -> str:- """Convert the processed DOM content to HTML."""- formatted_text = []-- if not include_attributes:- include_attributes = DEFAULT_INCLUDE_ATTRIBUTES-- def process_node(node: DOMBaseNode, depth: int) -> None:- next_depth = int(depth)- depth_str = depth * '\t'-- if isinstance(node, DOMElementNode):- # Add element with highlight_index- if node.highlight_index is not None:- next_depth += 1-- text = node.get_all_text_till_next_clickable_element()- attributes_html_str = None- if include_attributes:- attributes_to_include = {- key: str(value).strip()- for key, value in node.attributes.items()- if key in include_attributes and str(value).strip() != ''- }-- # If value of any of the attributes is the same as ANY other value attribute only include the one that appears first in include_attributes- # WARNING: heavy vibes, but it seems good enough for saving tokens (it kicks in hard when it's long text)-- # Pre-compute ordered keys that exist in both lists (faster than repeated lookups)- ordered_keys = [key for key in include_attributes if key in attributes_to_include]-- if len(ordered_keys) > 1: # Only process if we have multiple attributes- keys_to_remove = set() # Use set for O(1) lookups- seen_values = {} # value -> first_key_with_this_value-- for key in ordered_keys:- value = attributes_to_include[key]- if len(value) > 5: # to not remove false, true, etc- if value in seen_values:- # This value was already seen with an earlier key, so remove this key- keys_to_remove.add(key)- else:- # First time seeing this value, record it- seen_values[value] = key-- # Remove duplicate keys (no need to check existence since we know they exist)- for key in keys_to_remove:- del attributes_to_include[key]-- # Easy LLM optimizations- # if tag == role attribute, don't include it- if node.tag_name == attributes_to_include.get('role'):- del attributes_to_include['role']-- # Remove attributes that duplicate the node's text content- 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.items():- # Format as key1='value1' key2='value2'- attributes_html_str = ' '.join(- f'{key}={cap_text_length(value, 15)}' for key, value in attributes_to_include.items()- )-- # Build the line- if node.is_new:- highlight_indicator = f'*[{node.highlight_index}]'+@dataclass+class EnhancedDOMTreeNode:+ """+ Enchanced DOM tree node that contains information from AX, DOM, and Snapshot trees. It's mostly based on the types on DOM node type with enchanced data from AX and Snapshot trees.- else:- highlight_indicator = f'[{node.highlight_index}]'+ @dev when serializing check if the value is a valid value first!- line = f'{depth_str}{highlight_indicator}<{node.tag_name}'+ Learn more about the fields:+ - (DOM node) https://chromedevtools.github.io/devtools-protocol/tot/DOM/#type-BackendNode+ - (AX node) https://chromedevtools.github.io/devtools-protocol/tot/Accessibility/#type-AXNode+ - (Snapshot node) https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot/#type-DOMNode+ """- if attributes_html_str:- line += f' {attributes_html_str}'+ # region - DOM Node data+ node_id: int+ backend_node_id: int++ _node_type: NodeType+ """Node types, defined in `NodeType` enum."""+ node_name: str+ """Only applicable for `NodeType.ELEMENT_NODE`"""+ node_value: str+ """this is where the value from `NodeType.TEXT_NODE` is stored usually"""+ attributes: dict[str, str] | None+ """slightly changed from the original attributes to be more readable"""+ is_scrollable: bool | None+ """+ Whether the node is scrollable.+ """- if text:- # Add space before >text only if there were NO attributes added before- text = text.strip()- if not attributes_html_str:- line += ' '- line += f'>{text}'+ ## frames+ frame_id: str | None+ content_document: 'EnhancedDOMTreeNode | None'+ """+ Content document is the document inside a new iframe.+ """+ ## Shadow DOM+ shadow_root_type: ShadowRootType | None+ shadow_roots: list['EnhancedDOMTreeNode'] | None+ """+ Shadow roots are the shadow DOMs of the element.+ """- # Add space before /> only if neither attributes NOR text were added- elif not attributes_html_str:- line += ' '+ ## Navigation+ parent_node: 'EnhancedDOMTreeNode | None'+ children_nodes: list['EnhancedDOMTreeNode'] | None- # makes sense to have if the website has lots of text -> so the LLM knows which things are part of the same clickable element and which are not- line += ' />' # 1 token- formatted_text.append(line)+ # endregion - DOM Node data- # Process children regardless- for child in node.children:- process_node(child, next_depth)+ # region - AX Node data- elif isinstance(node, DOMTextNode):- # Add text only if it doesn't have a highlighted parent- if node.has_parent_with_highlight_index():- return+ # endregion - AX Node data- if node.parent and node.parent.is_visible and node.parent.is_top_element:- formatted_text.append(f'{depth_str}{node.text}')+ # region - Snapshot Node data- process_node(self, 0)- return '\n'.join(formatted_text)+ # endregion - Snapshot Node data-SelectorMap = dict[int, DOMElementNode]+class DOMState:+ pass-@dataclass-class DOMState:- element_tree: DOMElementNode- selector_map: SelectorMap+class DOMHistoryElement:+ passdiff --git a/pyproject.toml b/pyproject.tomlindex a9bd80107..1bf8d8d57 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -41,6 +41,7 @@ dependencies = ["google-auth-oauthlib>=1.2.2","mcp>=1.10.1","pypdf>=5.7.0",+ "cdp-use>=1.3.1",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/paste