Skip to content

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

clicking version - still missing iframe/shadow elements penetration

Gregor Žunič829ed138fda1
diff --git a/browser_use/agent/message_manager/tests.py b/browser_use/agent/message_manager/tests.py
index 65a913f9d..776e35a12 100644
--- a/browser_use/agent/message_manager/tests.py
+++ b/browser_use/agent/message_manager/tests.py
@@ -4,11 +4,10 @@ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_openai import AzureChatOpenAI, ChatOpenAI
from browser_use.agent.message_manager.service import MessageManager
-from browser_use.agent.message_manager.views import MessageMetadata
from browser_use.agent.prompts import SystemPrompt
from browser_use.agent.views import ActionResult
from browser_use.browser.views import BrowserState, TabInfo
-from browser_use.dom.views import DomContentItem
+from browser_use.dom.views import DOMElementNode, DOMTextNode
@pytest.fixture(
@@ -50,8 +49,15 @@ def test_add_state_message(message_manager: MessageManager):
state = BrowserState(
url='https://test.com',
title='Test Page',
- items=[DomContentItem(index=0, text='Test Content', is_text_only=True, depth=0)],
- selector_map={0: '//div[1]'},
+ element_tree=DOMElementNode(
+ tag_name='div',
+ attributes={},
+ children=[],
+ is_visible=True,
+ parent=None,
+ xpath='//div',
+ ),
+ selector_map={},
tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],
)
message_manager.add_state_message(state)
@@ -67,8 +73,15 @@ def test_add_state_with_memory_result(message_manager: MessageManager):
state = BrowserState(
url='https://test.com',
title='Test Page',
- items=[DomContentItem(index=0, text='Test Content', is_text_only=True, depth=0)],
- selector_map={0: '//div[1]'},
+ element_tree=DOMElementNode(
+ tag_name='div',
+ attributes={},
+ children=[],
+ is_visible=True,
+ parent=None,
+ xpath='//div',
+ ),
+ selector_map={},
tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],
)
result = ActionResult(extracted_content='Important content', include_in_memory=True)
@@ -89,8 +102,15 @@ def test_add_state_with_non_memory_result(message_manager: MessageManager):
state = BrowserState(
url='https://test.com',
title='Test Page',
- items=[DomContentItem(index=0, text='Test Content', is_text_only=True, depth=0)],
- selector_map={0: '//div[1]'},
+ element_tree=DOMElementNode(
+ tag_name='div',
+ attributes={},
+ children=[],
+ is_visible=True,
+ parent=None,
+ xpath='//div',
+ ),
+ selector_map={},
tabs=[TabInfo(page_id=1, url='https://test.com', title='Test Page')],
)
result = ActionResult(extracted_content='Temporary content', include_in_memory=False)
@@ -104,6 +124,7 @@ def test_add_state_with_non_memory_result(message_manager: MessageManager):
assert isinstance(messages[2], HumanMessage)
[email protected]('not sure how to fix this')
@pytest.mark.parametrize('max_tokens', [100000, 10000, 5000])
def test_token_overflow_handling_with_real_flow(message_manager: MessageManager, max_tokens):
"""Test handling of token overflow in a realistic message flow"""
@@ -116,20 +137,23 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
state = BrowserState(
url=f'https://test{i}.com',
title=f'Test Page {i}',
- items=[
- DomContentItem(
- index=j,
- text=f'Content {j} ' * (10 + i), # Increasing content length
- is_text_only=True,
- depth=1,
- )
- for j in range(5) # Multiple DOM items
- ],
+ element_tree=DOMElementNode(
+ tag_name='div',
+ attributes={},
+ children=[
+ DOMTextNode(
+ text=f'Content {j} ' * (10 + i), # Increasing content length
+ is_visible=True,
+ parent=None,
+ )
+ for j in range(5) # Multiple DOM items
+ ],
+ is_visible=True,
+ parent=None,
+ xpath='//div',
+ ),
selector_map={j: f'//div[{j}]' for j in range(5)},
tabs=[TabInfo(page_id=1, url=f'https://test{i}.com', title=f'Test Page {i}')],
- screenshot='data:image/png;base64,...'
- if i % 3 == 0
- else None, # Add screenshot every 3rd message
)
# Alternate between different types of results
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 0aee68ee0..87aa3e525 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -112,7 +112,7 @@ Current url: {self.state.url}
Available tabs:
{self.state.tabs}
Interactive elements:
-{self.state.dom_items_to_string()}
+{self.state.element_tree.clickable_elements_to_string()}
"""
if self.result:
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index d90ddb868..66a726c85 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -5,22 +5,18 @@ import logging
import os
import time
import uuid
-from datetime import datetime
from typing import Any, Optional, Type, TypeVar
from dotenv import load_dotenv
-from langchain_anthropic import ChatAnthropic
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import (
- AIMessage,
BaseMessage,
)
-from langchain_openai import ChatOpenAI
from openai import RateLimitError
from pydantic import BaseModel, ValidationError
from browser_use.agent.message_manager.service import MessageManager
-from browser_use.agent.prompts import AgentMessagePrompt, SystemPrompt
+from browser_use.agent.prompts import SystemPrompt
from browser_use.agent.views import (
ActionResult,
AgentError,
@@ -36,7 +32,7 @@ from browser_use.telemetry.views import (
AgentRunTelemetryEvent,
AgentStepErrorTelemetryEvent,
)
-from browser_use.utils import time_execution_async, time_execution_sync
+from browser_use.utils import time_execution_async
load_dotenv()
logger = logging.getLogger(__name__)
@@ -125,7 +121,7 @@ class Agent:
if result.extracted_content:
logger.info(f'📄 Result: {result.extracted_content}')
if result.is_done:
- logger.result(f'{result.extracted_content}')
+ logger.result(f'{result.extracted_content}') # type:ignore
self.consecutive_failures = 0
diff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.py
index e6af0cb4b..a02e387af 100644
--- a/browser_use/agent/tests.py
+++ b/browser_use/agent/tests.py
@@ -9,9 +9,8 @@ from browser_use.agent.views import (
)
from browser_use.browser.views import BrowserState, TabInfo
from browser_use.controller.registry.service import Registry
-from browser_use.controller.registry.views import ActionModel
from browser_use.controller.views import ClickElementAction, DoneAction, ExtractPageContentAction
-from browser_use.dom.views import DomContentItem, ProcessedDomContent
+from browser_use.dom.views import DOMElementNode
@pytest.fixture
@@ -21,11 +20,15 @@ def sample_browser_state():
title='Example Page',
tabs=[TabInfo(url='https://example.com', title='Example Page', page_id=1)],
screenshot='screenshot1.png',
- items=[
- DomContentItem(index=1, text='Click me', is_text_only=False, depth=0),
- DomContentItem(index=2, text='Some text', is_text_only=True, depth=1),
- ],
- selector_map={1: '//button[1]', 2: '//div[1]'},
+ element_tree=DOMElementNode(
+ tag_name='root',
+ is_visible=True,
+ parent=None,
+ xpath='',
+ attributes={},
+ children=[],
+ ),
+ selector_map={},
)
@@ -79,8 +82,15 @@ def sample_history(action_registry):
title='Page 1',
tabs=[TabInfo(url='https://example.com', title='Page 1', page_id=1)],
screenshot='screenshot1.png',
- items=[DomContentItem(index=1, text='Button', is_text_only=False, depth=0)],
- selector_map={1: '//button[1]'},
+ element_tree=DOMElementNode(
+ tag_name='root',
+ is_visible=True,
+ parent=None,
+ xpath='',
+ attributes={},
+ children=[],
+ ),
+ selector_map={},
),
),
AgentHistory(
@@ -102,8 +112,15 @@ def sample_history(action_registry):
title='Page 2',
tabs=[TabInfo(url='https://example.com/page2', title='Page 2', page_id=2)],
screenshot='screenshot2.png',
- items=[DomContentItem(index=2, text='Content', is_text_only=True, depth=0)],
- selector_map={2: '//div[1]'},
+ element_tree=DOMElementNode(
+ tag_name='root',
+ is_visible=True,
+ parent=None,
+ xpath='',
+ attributes={},
+ children=[],
+ ),
+ selector_map={},
),
),
AgentHistory(
@@ -121,8 +138,15 @@ def sample_history(action_registry):
title='Page 2',
tabs=[TabInfo(url='https://example.com/page2', title='Page 2', page_id=2)],
screenshot='screenshot3.png',
- items=[DomContentItem(index=3, text='Final', is_text_only=True, depth=0)],
- selector_map={3: '//div[2]'},
+ element_tree=DOMElementNode(
+ tag_name='root',
+ is_visible=True,
+ parent=None,
+ xpath='',
+ attributes={},
+ children=[],
+ ),
+ selector_map={},
),
),
]
diff --git a/browser_use/browser/service.py b/browser_use/browser/service.py
index da9d702c8..5ad929abc 100644
--- a/browser_use/browser/service.py
+++ b/browser_use/browser/service.py
@@ -13,7 +13,7 @@ from playwright.async_api import BrowserContext, ElementHandle, Page, Playwright
from browser_use.browser.views import BrowserError, BrowserState, TabInfo
from browser_use.dom.service import DomService
-from browser_use.dom.views import SelectorMap
+from browser_use.dom.views import DOMElementNode, SelectorMap
from browser_use.utils import time_execution_sync
logger = logging.getLogger(__name__)
@@ -50,7 +50,9 @@ class Browser:
# Instead of calling _update_state(), create an empty initial state
initial_state = BrowserState(
- items=[],
+ element_tree=DOMElementNode(
+ tag_name='root', is_visible=True, parent=None, xpath='', attributes={}, children=[]
+ ),
selector_map={},
url=page.url,
title=await page.title(),
@@ -258,10 +260,10 @@ class Browser:
screenshot_b64 = None
if use_vision:
- screenshot_b64 = await self.take_screenshot(selector_map=content.selector_map)
+ screenshot_b64 = await self.take_screenshot()
self.current_state = BrowserState(
- items=content.items,
+ element_tree=content.element_tree,
selector_map=content.selector_map,
url=page.url,
title=await page.title(),
@@ -273,17 +275,12 @@ class Browser:
# region - Browser Actions
- async def take_screenshot(
- self, selector_map: SelectorMap | None, full_page: bool = False
- ) -> str:
+ async def take_screenshot(self, full_page: bool = False) -> str:
"""
Returns a base64 encoded screenshot of the current page.
"""
page = await self.get_current_page()
- if selector_map:
- await self.highlight_selector_map_elements(selector_map)
-
screenshot = await page.screenshot(
full_page=full_page,
animations='disabled',
@@ -291,86 +288,44 @@ class Browser:
screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
- if selector_map:
- await self.remove_highlights()
-
- return screenshot_b64
-
- async def highlight_selector_map_elements(self, selector_map: SelectorMap):
- page = await self.get_current_page()
await self.remove_highlights()
- script = """
- const highlights = {
- """
-
- # Build the highlights object with all selectors and indices
- for index, selector in selector_map.items():
- # Adjusting the JavaScript code to accept variables
- script += f'"{index}": "{selector}",\n'
-
- script += """
- };
-
- for (const [index, selector] of Object.entries(highlights)) {
- const el = document.evaluate(selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
- if (!el) continue; // Skip if element not found
- el.style.outline = "2px solid red";
- el.setAttribute('browser-user-highlight-id', 'playwright-highlight');
-
- const label = document.createElement("div");
- label.className = 'playwright-highlight-label';
- label.style.position = "fixed";
- label.style.background = "red";
- label.style.color = "white";
- label.style.padding = "2px 6px";
- label.style.borderRadius = "10px";
- label.style.fontSize = "12px";
- label.style.zIndex = "9999999";
- label.textContent = index;
- const rect = el.getBoundingClientRect();
- label.style.top = (rect.top - 20) + "px";
- label.style.left = rect.left + "px";
- document.body.appendChild(label);
- }
- """
-
- await page.evaluate(script)
+ return screenshot_b64
async def remove_highlights(self):
"""
- Removes all highlight outlines and labels created by highlight_selector_map_elements
-
+ Removes all highlight overlays and labels created by the highlightElement function.
"""
page = await self.get_current_page()
await page.evaluate(
"""
- // Remove all highlight outlines
- const highlightedElements = document.querySelectorAll('[browser-user-highlight-id="playwright-highlight"]');
+ // Remove the highlight container and all its contents
+ const container = document.getElementById('playwright-highlight-container');
+ if (container) {
+ container.remove();
+ }
+
+ // Remove highlight attributes from elements
+ const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');
highlightedElements.forEach(el => {
- el.style.outline = '';
el.removeAttribute('browser-user-highlight-id');
});
-
-
- // Remove all labels
- const labels = document.querySelectorAll('.playwright-highlight-label');
- labels.forEach(label => label.remove());
"""
)
# endregion
# region - User Actions
-
- async def _input_text_by_xpath(self, xpath: str, text: str):
+ async def get_locate_element(self, element: DOMElementNode):
page = await self.get_current_page()
+ return await page.wait_for_selector(f'xpath={element.xpath}', timeout=5000, state='visible')
+ async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
try:
- element = await page.wait_for_selector(f'xpath={xpath}', timeout=5000, state='visible')
+ element = await self.get_locate_element(element_node)
if element is None:
- raise Exception(f'Element with xpath: {xpath} not found')
+ raise Exception(f'Element with xpath: {element_node.xpath} not found')
await element.scroll_into_view_if_needed(timeout=2500)
await element.fill('')
@@ -379,20 +334,20 @@ class Browser:
except Exception as e:
raise Exception(
- f'Failed to input text into element with xpath: {xpath}. Error: {str(e)}'
+ f'Failed to input text into element with xpath: {element_node.xpath}. Error: {str(e)}'
)
- async def _click_element_by_xpath(self, xpath: str):
+ async def _click_element_node(self, element_node: DOMElementNode):
"""
Optimized method to click an element using xpath.
"""
page = await self.get_current_page()
try:
- element = await page.wait_for_selector(f'xpath={xpath}', timeout=5000, state='visible')
+ element = await self.get_locate_element(element_node)
if element is None:
- raise Exception(f'Element with xpath: {xpath} not found')
+ raise Exception(f'Element with xpath: {element_node.xpath} not found')
# await element.scroll_into_view_if_needed()
@@ -411,7 +366,9 @@ class Browser:
raise Exception(f'Failed to click element: {str(e)}')
except Exception as e:
- raise Exception(f'Failed to click element with xpath: {xpath}. Error: {str(e)}')
+ raise Exception(
+ f'Failed to click element with xpath: {element_node.xpath}. Error: {str(e)}'
+ )
async def get_tabs_info(self) -> list[TabInfo]:
"""Get information about all tabs"""
@@ -464,7 +421,7 @@ class Browser:
async def get_xpath(self, index: int) -> str:
selector_map = await self.get_selector_map()
- return selector_map[index]
+ return selector_map[index].xpath
async def get_element_by_index(self, index: int) -> ElementHandle | None:
page = await self.get_current_page()
diff --git a/browser_use/browser/tests/playwright_test.py b/browser_use/browser/tests/playwright_test.py
deleted file mode 100644
index 4ac45a937..000000000
--- a/browser_use/browser/tests/playwright_test.py
+++ /dev/null
@@ -1,54 +0,0 @@
-import time
-
-import pytest
-from playwright.async_api import Page
-
-from browser_use.dom.service import DomService
-
-
[email protected](scope='session')
-def browser_type_launch_args():
- return {'headless': False}
-
-
-async def test_has_title(page: Page):
- dom_service = DomService(page)
-
- await page.goto('https://www.immobilienscout24.de')
- await page.wait_for_timeout(2000)
-
- # Get all DOM content including all shadow roots recursively
- start_time = time.time()
- # wait for the page to load
- await page.wait_for_load_state('load')
- full_content = await dom_service._get_html_content()
- # full_content = page.evaluate("""() => {
- # function getAllContent(root) {
- # let content = '';
- # // Get all elements in the current root
- # const elements = root.querySelectorAll('*');
-
- # elements.forEach(element => {
- # // Add the element's outer HTML
- # content += element.outerHTML;
- # // If element has shadow root, recursively get its content
- # if (element.shadowRoot) {
- # content += `\\n<!-- Shadow DOM for ${element.tagName} -->\\n`;
- # content += getAllContent(element.shadowRoot);
- # content += `\\n<!-- End Shadow DOM for ${element.tagName} -->\\n`;
- # }
- # });
- # return content;
- # }
- # return getAllContent(document);
- # }""")
- end_time = time.time()
-
- print(full_content)
- print(f'Time taken to get DOM content: {end_time - start_time:.2f} seconds')
-
- elements = dom_service._process_content(full_content)
-
- print(elements)
-
- input('Press Enter to continue...')
diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.py
index 76ded4482..cf441bfdc 100644
--- a/browser_use/browser/tests/test_clicks.py
+++ b/browser_use/browser/tests/test_clicks.py
@@ -18,7 +18,7 @@ async def test_highlight_elements():
# await page.goto('https://immobilienscout24.de')
await page.goto('https://kayak.com')
- time.sleep(3)
+ time.sleep(1.5)
# browser._click_element_by_xpath(
# '/html/body/div[5]/div/div[2]/div/div/div[3]/div/div[1]/button[1]'
# )
@@ -27,20 +27,21 @@ async def test_highlight_elements():
while True:
state = await browser.get_state()
- await time_execution_sync('highlight_selector_map_elements')(
- browser.highlight_selector_map_elements
- )(state.selector_map)
+ # await time_execution_sync('highlight_selector_map_elements')(
+ # browser.highlight_selector_map_elements
+ # )(state.selector_map)
- print(state.dom_items_to_string(use_tabs=False))
+ # print(state.dom_items_to_string(use_tabs=False))
# print(state.selector_map)
# Find and print duplicate XPaths
xpath_counts = {}
for selector in state.selector_map.values():
- if selector in xpath_counts:
- xpath_counts[selector] += 1
+ xpath = selector.xpath
+ if xpath in xpath_counts:
+ xpath_counts[xpath] += 1
else:
- xpath_counts[selector] = 1
+ xpath_counts[xpath] = 1
print('\nDuplicate XPaths found:')
for xpath, count in xpath_counts.items():
@@ -57,9 +58,4 @@ async def test_highlight_elements():
# check if index of selector map are the same as index of items in dom_items
- indcies = list(state.selector_map.keys())
- dom_items = state.items
- dom_indices = [item.index for item in dom_items if not item.is_text_only]
- assert indcies == dom_indices, 'Indices of selector map and dom items do not match'
-
- await browser._click_element_by_xpath(xpath)
+ await browser._click_element_node(xpath)
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index f87819dd8..0e1ab239f 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -1,8 +1,9 @@
+from dataclasses import dataclass
from typing import Optional
from pydantic import BaseModel
-from browser_use.dom.views import ProcessedDomContent
+from browser_use.dom.views import DOMState
# Pydantic
@@ -14,20 +15,21 @@ class TabInfo(BaseModel):
title: str
-class BrowserState(ProcessedDomContent):
+@dataclass
+class BrowserState(DOMState):
url: str
title: str
tabs: list[TabInfo]
screenshot: Optional[str] = None
- def model_dump(self) -> dict:
- dump = super().model_dump()
- # Add a summary of available tabs
- if self.tabs:
- dump['available_tabs'] = [
- f'Tab {i+1}: {tab.title} ({tab.url})' for i, tab in enumerate(self.tabs)
- ]
- return dump
+ # def model_dump(self) -> dict:
+ # dump = super().model_dump()
+ # # Add a summary of available tabs
+ # if self.tabs:
+ # dump['available_tabs'] = [
+ # f'Tab {i+1}: {tab.title} ({tab.url})' for i, tab in enumerate(self.tabs)
+ # ]
+ # return dump
class BrowserError(Exception):
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index fa472cd41..56a818cc6 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -65,15 +65,15 @@ class Controller:
f'Element with index {params.index} does not exist - retry or use alternative actions'
)
- xpath = state.selector_map[params.index]
+ element_node = state.selector_map[params.index]
initial_pages = len(session.context.pages)
msg = None
for _ in range(params.num_clicks):
try:
- await browser._click_element_by_xpath(xpath)
- msg = f'🖱️ Clicked element {params.index}: {xpath}'
+ await browser._click_element_node(element_node)
+ msg = f'🖱️ Clicked element {params.index}: {element_node.xpath}'
if params.num_clicks > 1:
msg += f' ({_ + 1}/{params.num_clicks} clicks)'
except Exception as e:
@@ -95,9 +95,9 @@ class Controller:
f'Element index {params.index} does not exist - retry or use alternative actions'
)
- xpath = state.selector_map[params.index]
- await browser._input_text_by_xpath(xpath, params.text)
- msg = f'⌨️ Input "{params.text}" into {params.index}: {xpath}'
+ element_node = state.selector_map[params.index]
+ await browser._input_text_element_node(element_node, params.text)
+ msg = f'⌨️ Input "{params.text}" into {params.index}: {element_node.xpath}'
return ActionResult(extracted_content=msg)
# Tab Management Actions
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
new file mode 100644
index 000000000..a60da331c
--- /dev/null
+++ b/browser_use/dom/buildDomTree.js
@@ -0,0 +1,381 @@
+let highlightIndex = 0;
+
+function highlightElement(element, index) {
+ // Create or get highlight container
+ let container = document.getElementById('playwright-highlight-container');
+ if (!container) {
+ container = document.createElement('div');
+ container.id = 'playwright-highlight-container';
+ container.style.position = 'fixed';
+ container.style.pointerEvents = 'none';
+ container.style.top = '0';
+ container.style.left = '0';
+ container.style.width = '100%';
+ container.style.height = '100%';
+ container.style.zIndex = '2147483647'; // Maximum z-index value
+ document.documentElement.appendChild(container);
+ }
+
+ // Create highlight overlay
+ const overlay = document.createElement('div');
+ overlay.style.position = 'absolute';
+ overlay.style.border = '2px solid red';
+ overlay.style.pointerEvents = 'none';
+ overlay.style.boxSizing = 'border-box';
+
+ // Position overlay based on element
+ const rect = element.getBoundingClientRect();
+ overlay.style.top = `${rect.top}px`;
+ overlay.style.left = `${rect.left}px`;
+ overlay.style.width = `${rect.width}px`;
+ overlay.style.height = `${rect.height}px`;
+
+ // Create label
+ const label = document.createElement('div');
+ label.className = 'playwright-highlight-label';
+ label.style.position = 'absolute';
+ label.style.background = 'red';
+ label.style.color = 'white';
+ label.style.padding = '2px 6px';
+ label.style.borderRadius = '10px';
+ label.style.fontSize = '12px';
+ label.textContent = index;
+ label.style.top = `${rect.top - 20}px`;
+ label.style.left = `${rect.left}px`;
+
+ // Add to container
+ container.appendChild(overlay);
+ container.appendChild(label);
+
+ // Store reference for cleanup
+ element.setAttribute('browser-user-highlight-id', `playwright-highlight-${index}`);
+
+ return index + 1;
+}
+
+
+// Helper function to generate XPath as a tree
+function getXPathTree(element, stopAtBoundary = true) {
+ 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;
+ }
+
+ let index = 0;
+ let sibling = currentElement.previousSibling;
+ while (sibling) {
+ if (sibling.nodeType === Node.ELEMENT_NODE &&
+ sibling.nodeName === currentElement.nodeName) {
+ index++;
+ }
+ sibling = sibling.previousSibling;
+ }
+
+ const tagName = currentElement.nodeName.toLowerCase();
+ const xpathIndex = index > 0 ? `[${index + 1}]` : '';
+ segments.unshift(`${tagName}${xpathIndex}`);
+
+ currentElement = currentElement.parentNode;
+ }
+
+ return segments.join('/');
+}
+
+// Helper function to check if element is accepted
+function isElementAccepted(element) {
+ const leafElementDenyList = new Set(['svg', 'script', 'style', 'link', 'meta']);
+ return !leafElementDenyList.has(element.tagName.toLowerCase());
+}
+
+// Helper function to check if element is interactive
+function isInteractiveElement(element) {
+ // Base interactive elements and roles
+ const interactiveElements = new Set([
+ 'a', 'button', 'details', 'embed', 'input', 'label',
+ 'menu', 'menuitem', 'object', 'select', 'textarea', 'summary'
+ ]);
+
+ const interactiveRoles = new Set([
+ 'button', 'menu', 'menuitem', 'link', 'checkbox', 'radio',
+ 'slider', 'tab', 'tabpanel', 'textbox', 'combobox', 'grid',
+ 'listbox', 'option', 'progressbar', 'scrollbar', 'searchbox',
+ 'switch', 'tree', 'treeitem', 'spinbutton', 'tooltip',
+ 'menuitemcheckbox', 'menuitemradio'
+ ]);
+
+ const tagName = element.tagName.toLowerCase();
+ const role = element.getAttribute('role');
+ const ariaRole = element.getAttribute('aria-role');
+ const tabIndex = element.getAttribute('tabindex');
+
+ // Basic role/attribute checks
+ const hasInteractiveRole = interactiveElements.has(tagName) ||
+ interactiveRoles.has(role) ||
+ interactiveRoles.has(ariaRole) ||
+ tabIndex === '0';
+
+ if (hasInteractiveRole) return true;
+
+ // Get computed style
+ const style = window.getComputedStyle(element);
+
+ // Check if element has click-like styling
+ // const hasClickStyling = style.cursor === 'pointer' ||
+ // element.style.cursor === 'pointer' ||
+ // style.pointerEvents !== 'none';
+
+ // Check for event listeners
+ const hasClickHandler = element.onclick !== null ||
+ element.getAttribute('onclick') !== null ||
+ element.hasAttribute('ng-click') ||
+ element.hasAttribute('@click') ||
+ element.hasAttribute('v-on:click');
+
+ // Helper function to safely get event listeners
+ function getEventListeners(el) {
+ try {
+ // Try to get listeners using Chrome DevTools API
+ return window.getEventListeners?.(el) || {};
+ } catch (e) {
+ // Fallback: check for common event properties
+ const listeners = {};
+
+ // List of common event types to check
+ const eventTypes = [
+ 'click', 'mousedown', 'mouseup',
+ 'touchstart', 'touchend',
+ 'keydown', 'keyup', 'focus', 'blur'
+ ];
+
+ for (const type of eventTypes) {
+ const handler = el[`on${type}`];
+ if (handler) {
+ listeners[type] = [{
+ listener: handler,
+ useCapture: false
+ }];
+ }
+ }
+
+ return listeners;
+ }
+ }
+
+ // Check for click-related events on the element itself
+ const listeners = getEventListeners(element);
+ const hasClickListeners = listeners && (
+ listeners.click?.length > 0 ||
+ listeners.mousedown?.length > 0 ||
+ listeners.mouseup?.length > 0 ||
+ listeners.touchstart?.length > 0 ||
+ listeners.touchend?.length > 0
+ );
+
+ // Check for ARIA properties that suggest interactivity
+ const hasAriaProps = element.hasAttribute('aria-expanded') ||
+ element.hasAttribute('aria-pressed') ||
+ element.hasAttribute('aria-selected') ||
+ element.hasAttribute('aria-checked');
+
+ // Check for form-related functionality
+ const isFormRelated = element.form !== undefined ||
+ element.hasAttribute('contenteditable') ||
+ style.userSelect !== 'none';
+
+ // Check if element is draggable
+ const isDraggable = element.draggable ||
+ element.getAttribute('draggable') === 'true';
+
+ return hasAriaProps ||
+ // hasClickStyling ||
+ hasClickHandler ||
+ hasClickListeners ||
+ // isFormRelated ||
+ isDraggable;
+
+}
+
+// Helper function to check if element is visible
+function isElementVisible(element) {
+ const style = window.getComputedStyle(element);
+ return element.offsetWidth > 0 &&
+ element.offsetHeight > 0 &&
+ style.visibility !== 'hidden' &&
+ style.display !== 'none';
+}
+
+// Helper function to check if element is the top element at its position
+function isTopElement(element) {
+ // 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 rect = element.getBoundingClientRect();
+ const point = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
+
+ try {
+ // Use shadow root's elementFromPoint to check within shadow DOM context
+ const topEl = shadowRoot.elementFromPoint(point.x, point.y);
+ if (!topEl) return false;
+
+ // Check if the element or any of its parents match our target element
+ let current = topEl;
+ while (current && current !== shadowRoot) {
+ if (current === element) return true;
+ current = current.parentElement;
+ }
+ return false;
+ } catch (e) {
+ return true; // If we can't determine, consider it visible
+ }
+ }
+
+ // Regular DOM elements
+ const rect = element.getBoundingClientRect();
+ const point = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
+
+ try {
+ const topEl = document.elementFromPoint(point.x, point.y);
+ 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;
+ }
+}
+
+// Helper function to check if text node is visible
+function isTextNodeVisible(textNode) {
+ const range = document.createRange();
+ range.selectNodeContents(textNode);
+ const rect = range.getBoundingClientRect();
+
+ return rect.width !== 0 &&
+ rect.height !== 0 &&
+ rect.top >= 0 &&
+ rect.top <= window.innerHeight &&
+ textNode.parentElement.checkVisibility({
+ checkOpacity: true,
+ checkVisibilityCSS: true
+ });
+}
+
+
+// Function to traverse the DOM and create nested JSON
+function buildDomTree(node, parentIframe = null) {
+ if (!node) return null;
+
+ // Special case for text nodes
+ if (node.nodeType === Node.TEXT_NODE) {
+ const textContent = node.textContent.trim();
+ if (textContent && isTextNodeVisible(node)) {
+ // Highlight text node's parent element since we can't highlight text nodes directly
+ // highlightIndex = highlightElement(node.parentElement, highlightIndex);
+ return {
+ type: "TEXT_NODE",
+ text: textContent,
+ isVisible: true,
+ // highlightIndex: highlightIndex - 1
+ };
+ }
+ return null;
+ }
+
+ // Check if element is accepted
+ if (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {
+ return null;
+ }
+
+ const nodeData = {
+ tagName: node.tagName ? node.tagName.toLowerCase() : null,
+ attributes: {},
+ xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node, true) : null,
+ children: [],
+ };
+
+ // Copy all attributes if the node is an element
+ if (node.nodeType === Node.ELEMENT_NODE && node.attributes) {
+ for (const attr of node.attributes) {
+ nodeData.attributes[attr.name] = attr.value;
+ }
+ }
+
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ const isInteractive = isInteractiveElement(node);
+ const isVisible = isElementVisible(node);
+ const isTop = isTopElement(node);
+
+ nodeData.isInteractive = isInteractive;
+ nodeData.isVisible = isVisible;
+ nodeData.isTopElement = isTop;
+
+ // Highlight if element meets all criteria
+ if (isInteractive && isVisible && isTop) {
+ highlightIndex = highlightElement(node, highlightIndex);
+ nodeData.highlightIndex = highlightIndex - 1;
+ }
+ }
+
+ // Only add iframeContext if we're inside an iframe
+ if (parentIframe) {
+ nodeData.iframeContext = `iframe[src="${parentIframe.src || ''}"]`;
+ }
+
+ // Only add shadowRoot field if it exists
+ if (node.shadowRoot) {
+ nodeData.shadowRoot = true;
+ }
+
+ // Handle shadow DOM
+ if (node.shadowRoot) {
+ const shadowChildren = Array.from(node.shadowRoot.childNodes).map(child =>
+ buildDomTree(child, parentIframe)
+ );
+ nodeData.children.push(...shadowChildren);
+ }
+
+ // Handle iframes
+ if (node.tagName === 'IFRAME') {
+ 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);
+ }
+ } catch (e) {
+ console.warn('Unable to access iframe:', node);
+ }
+ } else {
+ // Traverse child nodes
+ const children = Array.from(node.childNodes).map(child =>
+ buildDomTree(child, parentIframe)
+ );
+ nodeData.children.push(...children);
+ }
+
+ return nodeData;
+}
+
+() => {
+
+ // Start from the document body
+ return buildDomTree(document.body);
+}
\ No newline at end of file
diff --git a/browser_use/dom/process_dom.js b/browser_use/dom/process_dom.js
deleted file mode 100644
index 99c35b7f6..000000000
--- a/browser_use/dom/process_dom.js
+++ /dev/null
@@ -1,349 +0,0 @@
-let highlightIndex = 0;
-
-function highlightElement(element, index) {
- element.style.outline = "2px solid red";
- element.setAttribute('browser-user-highlight-id', 'playwright-highlight');
-
- const label = document.createElement("div");
- label.className = 'playwright-highlight-label';
- label.style.position = "fixed";
- label.style.background = "red";
- label.style.color = "white";
- label.style.padding = "2px 6px";
- label.style.borderRadius = "10px";
- label.style.fontSize = "12px";
- label.style.zIndex = "9999999";
- label.textContent = index;
-
- const rect = element.getBoundingClientRect();
- label.style.top = (rect.top - 20) + "px";
- label.style.left = rect.left + "px";
- document.body.appendChild(label);
-
- return index + 1;
-}
-
-() => {
-
- // Helper function to generate XPath as a tree
- function getXPathTree(element, stopAtBoundary = true) {
- 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;
- }
-
- let index = 0;
- let sibling = currentElement.previousSibling;
- while (sibling) {
- if (sibling.nodeType === Node.ELEMENT_NODE &&
- sibling.nodeName === currentElement.nodeName) {
- index++;
- }
- sibling = sibling.previousSibling;
- }
-
- const tagName = currentElement.nodeName.toLowerCase();
- const xpathIndex = index > 0 ? `[${index + 1}]` : '';
- segments.unshift(`${tagName}${xpathIndex}`);
-
- currentElement = currentElement.parentNode;
- }
-
- return segments.join('/');
- }
-
- // Helper function to check if element is accepted
- function isElementAccepted(element) {
- const leafElementDenyList = new Set(['svg', 'script', 'style', 'link', 'meta']);
- return !leafElementDenyList.has(element.tagName.toLowerCase());
- }
-
- // Helper function to check if element is interactive
- function isInteractiveElement(element) {
- // Base interactive elements and roles
- const interactiveElements = new Set([
- 'a', 'button', 'details', 'embed', 'input', 'label',
- 'menu', 'menuitem', 'object', 'select', 'textarea', 'summary'
- ]);
-
- const interactiveRoles = new Set([
- 'button', 'menu', 'menuitem', 'link', 'checkbox', 'radio',
- 'slider', 'tab', 'tabpanel', 'textbox', 'combobox', 'grid',
- 'listbox', 'option', 'progressbar', 'scrollbar', 'searchbox',
- 'switch', 'tree', 'treeitem', 'spinbutton', 'tooltip',
- 'menuitemcheckbox', 'menuitemradio'
- ]);
-
- const tagName = element.tagName.toLowerCase();
- const role = element.getAttribute('role');
- const ariaRole = element.getAttribute('aria-role');
- const tabIndex = element.getAttribute('tabindex');
-
- // Basic role/attribute checks
- const hasInteractiveRole = interactiveElements.has(tagName) ||
- interactiveRoles.has(role) ||
- interactiveRoles.has(ariaRole) ||
- tabIndex === '0';
-
- if (hasInteractiveRole) return true;
-
- // Get computed style
- const style = window.getComputedStyle(element);
-
- // Check if element has click-like styling
- // const hasClickStyling = style.cursor === 'pointer' ||
- // element.style.cursor === 'pointer' ||
- // style.pointerEvents !== 'none';
-
- // Check for event listeners
- const hasClickHandler = element.onclick !== null ||
- element.getAttribute('onclick') !== null ||
- element.hasAttribute('ng-click') ||
- element.hasAttribute('@click') ||
- element.hasAttribute('v-on:click');
-
- // Helper function to safely get event listeners
- function getEventListeners(el) {
- try {
- // Try to get listeners using Chrome DevTools API
- return window.getEventListeners?.(el) || {};
- } catch (e) {
- // Fallback: check for common event properties
- const listeners = {};
-
- // List of common event types to check
- const eventTypes = [
- 'click', 'mousedown', 'mouseup',
- 'touchstart', 'touchend', 'keydown',
- 'keyup', 'focus', 'blur'
- ];
-
- for (const type of eventTypes) {
- const handler = el[`on${type}`];
- if (handler) {
- listeners[type] = [{
- listener: handler,
- useCapture: false
- }];
- }
- }
-
- return listeners;
- }
- }
-
- // Check for click-related events on the element itself
- const listeners = getEventListeners(element);
- const hasClickListeners = listeners && (
- listeners.click?.length > 0 ||
- listeners.mousedown?.length > 0 ||
- listeners.mouseup?.length > 0 ||
- listeners.touchstart?.length > 0 ||
- listeners.touchend?.length > 0
- );
-
- // Check for ARIA properties that suggest interactivity
- const hasAriaProps = element.hasAttribute('aria-expanded') ||
- element.hasAttribute('aria-pressed') ||
- element.hasAttribute('aria-selected') ||
- element.hasAttribute('aria-checked');
-
- // Check for form-related functionality
- const isFormRelated = element.form !== undefined ||
- element.hasAttribute('contenteditable') ||
- style.userSelect !== 'none';
-
- // Check if element is draggable
- const isDraggable = element.draggable ||
- element.getAttribute('draggable') === 'true';
-
- return hasAriaProps ||
- // hasClickStyling ||
- hasClickHandler ||
- hasClickListeners ||
- // isFormRelated ||
- isDraggable;
-
- }
-
- // Helper function to check if element is visible
- function isElementVisible(element) {
- const style = window.getComputedStyle(element);
- return element.offsetWidth > 0 &&
- element.offsetHeight > 0 &&
- style.visibility !== 'hidden' &&
- style.display !== 'none';
- }
-
- // Helper function to check if element is the top element at its position
- function isTopElement(element) {
- // 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 rect = element.getBoundingClientRect();
- const point = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
-
- try {
- // Use shadow root's elementFromPoint to check within shadow DOM context
- const topEl = shadowRoot.elementFromPoint(point.x, point.y);
- if (!topEl) return false;
-
- // Check if the element or any of its parents match our target element
- let current = topEl;
- while (current && current !== shadowRoot) {
- if (current === element) return true;
- current = current.parentElement;
- }
- return false;
- } catch (e) {
- return true; // If we can't determine, consider it visible
- }
- }
-
- // Regular DOM elements
- const rect = element.getBoundingClientRect();
- const point = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
-
- try {
- const topEl = document.elementFromPoint(point.x, point.y);
- 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;
- }
- }
-
- // Helper function to check if text node is visible
- function isTextNodeVisible(textNode) {
- const range = document.createRange();
- range.selectNodeContents(textNode);
- const rect = range.getBoundingClientRect();
-
- return rect.width !== 0 &&
- rect.height !== 0 &&
- rect.top >= 0 &&
- rect.top <= window.innerHeight &&
- textNode.parentElement.checkVisibility({
- checkOpacity: true,
- checkVisibilityCSS: true
- });
- }
-
- // Function to traverse the DOM and create nested JSON
- function buildDomTree(node, parentIframe = null) {
- if (!node) return null;
-
- // Special case for text nodes
- if (node.nodeType === Node.TEXT_NODE) {
- const textContent = node.textContent.trim();
- if (textContent && isTextNodeVisible(node)) {
- // Highlight text node's parent element since we can't highlight text nodes directly
- // highlightIndex = highlightElement(node.parentElement, highlightIndex);
- return {
- type: "TEXT_NODE",
- text: textContent,
- isVisible: true,
- // highlightIndex: highlightIndex - 1
- };
- }
- return null;
- }
-
- // Check if element is accepted
- if (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {
- return null;
- }
-
- const nodeData = {
- tagName: node.tagName ? node.tagName.toLowerCase() : null,
- attributes: {},
- xpath: node.nodeType === Node.ELEMENT_NODE ? getXPathTree(node, true) : null,
- children: [],
- };
-
- if (node.nodeType === Node.ELEMENT_NODE) {
- const isInteractive = isInteractiveElement(node);
- const isVisible = isElementVisible(node);
- const isTop = isTopElement(node);
-
- nodeData.isInteractive = isInteractive;
- nodeData.isVisible = isVisible;
- nodeData.isTopElement = isTop;
-
- // Highlight if element meets all criteria
- if (isInteractive && isVisible && isTop) {
- highlightIndex = highlightElement(node, highlightIndex);
- nodeData.highlightIndex = highlightIndex - 1;
- }
- }
-
- // Copy all attributes if the node is an element
- if (node.nodeType === Node.ELEMENT_NODE && node.attributes) {
- for (const attr of node.attributes) {
- nodeData.attributes[attr.name] = attr.value;
- }
- }
-
- // Only add iframeContext if we're inside an iframe
- if (parentIframe) {
- nodeData.iframeContext = `iframe[src="${parentIframe.src || ''}"]`;
- }
-
- // Only add shadowRoot field if it exists
- if (node.shadowRoot) {
- nodeData.shadowRoot = true;
- }
-
- // Handle shadow DOM
- if (node.shadowRoot) {
- const shadowChildren = Array.from(node.shadowRoot.childNodes).map(child =>
- buildDomTree(child, parentIframe)
- );
- nodeData.children.push(...shadowChildren);
- }
-
- // Handle iframes
- if (node.tagName === 'IFRAME') {
- 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);
- }
- } catch (e) {
- console.warn('Unable to access iframe:', node);
- }
- } else {
- // Traverse child nodes
- const children = Array.from(node.childNodes).map(child =>
- buildDomTree(child, parentIframe)
- );
- nodeData.children.push(...children);
- }
-
- return nodeData;
- }
-
- // Start from the document body
- return buildDomTree(document.body);
-}
\ No newline at end of file
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index d17b6e69a..6cf6946d6 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -1,18 +1,15 @@
-import json
import logging
from typing import Optional
-from bs4 import BeautifulSoup, NavigableString, PageElement, Tag
from playwright.async_api import Page
from browser_use.dom.views import (
- BatchCheckResults,
- DomContentItem,
- ElementCheckResult,
- ProcessedDomContent,
- TextCheckResult,
+ DOMBaseNode,
+ DOMElementNode,
+ DOMState,
+ DOMTextNode,
+ SelectorMap,
)
-from browser_use.utils import time_execution_async
logger = logging.getLogger(__name__)
@@ -22,368 +19,74 @@ class DomService:
self.page = page
self.xpath_cache = {}
- async def get_clickable_elements(self) -> ProcessedDomContent:
- self.xpath_cache = {}
- html_content = await self._get_html_content()
- return await self._process_content(html_content)
-
- async def _get_html_content(self, with_shadow_roots: bool = True) -> str:
- """
- Get all DOM content including all shadow roots recursively.
-
- @param with_shadow_roots: If you want to include shadow roots in the content it's a bit slower but worth it in most cases.
- """
- if with_shadow_roots:
- full_content = await self.page.evaluate("""() => {
- function getAllContent(root) {
- if (!root) return '';
- let content = root.innerHTML || '';
-
- // Get all elements with shadow roots
- const elements = root.querySelectorAll('*');
- elements.forEach(element => {
- if (element.shadowRoot) {
- // Add a marker for shadow root start
- content += `<shadow-root host="${element.tagName.toLowerCase()}">`;
- content += getAllContent(element.shadowRoot);
- content += '</shadow-root>';
- }
- });
-
- return content;
- }
-
- return `<html><body>${getAllContent(document.body)}</body></html>`;
- }""")
- return full_content
- return await self.page.content()
-
- @time_execution_async('--_process_content')
- async def _process_content(self, html_content: str) -> ProcessedDomContent:
- soup = BeautifulSoup(html_content, 'html.parser')
-
- output_items: list[DomContentItem] = []
- selector_map: dict[int, str] = {}
- current_index = 0
-
- # Collectors for batch processing with order tracking
- interactive_elements: dict[str, tuple[Tag, int]] = {} # xpath -> (element, order)
- text_nodes: dict[str, tuple[NavigableString, int]] = {} # xpath -> (text_node, order)
- xpath_order_counter = 0 # Track order of appearance
-
- dom_queue: list[tuple[PageElement, list, Optional[str]]] = (
- [(element, [], None) for element in reversed(list(soup.body.children))]
- if soup.body
- else []
- )
-
- # First pass: collect all elements that need checking
- while dom_queue:
- element, path_indices, parent_xpath = dom_queue.pop()
-
- if isinstance(element, Tag):
- if not self._is_element_accepted(element):
- element.decompose()
- continue
-
- siblings = (
- list(element.parent.find_all(element.name, recursive=False))
- if element.parent
- else []
- )
- sibling_index = siblings.index(element) + 1 if siblings else 1
- current_path = path_indices + [(element.name, sibling_index)]
- element_xpath = '//' + '/'.join(f'{tag}[{idx}]' for tag, idx in current_path)
-
- # Add children to queue with their path information
- for child in reversed(list(element.children)):
- dom_queue.append((child, current_path, element_xpath)) # Pass parent's xpath
-
- # Collect interactive elements with their order
- if (
- self._is_interactive_element(element) or self._is_leaf_element(element)
- ) and self._is_active(element):
- interactive_elements[element_xpath] = (element, xpath_order_counter)
- xpath_order_counter += 1
-
- elif isinstance(element, NavigableString) and element.strip():
- if element.parent and element.parent not in [e[0] for e in dom_queue]:
- if parent_xpath:
- text_nodes[parent_xpath] = (element, xpath_order_counter)
- xpath_order_counter += 1
-
- # Batch check all elements
- element_results = await self._batch_check_elements(interactive_elements)
- text_results = await self._batch_check_texts(text_nodes)
-
- # Create ordered results
- ordered_results: list[
- tuple[int, str, bool, str, int, bool]
- ] = [] # [(order, xpath, is_clickable, content, depth, is_text_only), ...]
+ async def get_clickable_elements(self) -> DOMState:
+ element_tree = await self._build_dom_tree()
+ selector_map = self._create_selector_map(element_tree)
- # Process interactive elements
- for xpath, (element, order) in interactive_elements.items():
- if xpath in element_results.elements:
- result = element_results.elements[xpath]
- if result.isVisible and result.isTopElement:
- text_content = self._extract_text_from_all_children(element)
- tag_name = element.name
- attributes = self._get_all_attributes(element)
- output_string = f"<{tag_name}{' ' + attributes if attributes else ''}>{text_content}</{tag_name}>"
+ return DOMState(element_tree=element_tree, selector_map=selector_map)
- depth = len(xpath.split('/')) - 2
- ordered_results.append((order, xpath, True, output_string, depth, False))
+ async def _build_dom_tree(self) -> DOMElementNode:
+ with open('browser_use/dom/buildDomTree.js', 'r') as f:
+ js_code = f.read()
- # Process text nodes
- for xpath, (text_node, order) in text_nodes.items():
- if xpath in text_results.texts:
- result = text_results.texts[xpath]
- if result.isVisible:
- text_content = text_node.strip()
- if text_content:
- depth = len(xpath.split('/')) - 2
- ordered_results.append((order, xpath, False, text_content, depth, True))
+ eval_page = await self.page.evaluate(js_code) # This is quite big, so be careful
+ html_to_dict = self._parse_node(eval_page)
- # Sort by original order
- ordered_results.sort(key=lambda x: x[0])
+ if html_to_dict is None or not isinstance(html_to_dict, DOMElementNode):
+ raise ValueError('Failed to parse HTML to dictionary')
- # Build final output maintaining order
- for i, (_, xpath, is_clickable, content, depth, is_text_only) in enumerate(ordered_results):
- output_items.append(
- DomContentItem(
- index=i,
- text=content,
- # clickable=is_clickable,
- depth=depth,
- is_text_only=is_text_only,
- )
- )
- # if is_clickable: # Only add clickable elements to selector map
- # TODO: make this right, for now we add all elements (except text) to selector map
- if not is_text_only:
- selector_map[i] = xpath
-
- return ProcessedDomContent(items=output_items, selector_map=selector_map)
+ return html_to_dict
- async def _batch_check_elements(
- self, elements: dict[str, tuple[Tag, int]]
- ) -> BatchCheckResults:
- if not elements:
- return BatchCheckResults(elements={}, texts={})
+ def _create_selector_map(self, element_tree: DOMElementNode) -> SelectorMap:
+ selector_map = {}
- check_script = """
- (function() {
- const results = {};
- const elements = %s;
-
- for (const [xpath, elementData] of Object.entries(elements)) {
- const element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
- if (!element) continue;
-
- const isVisible = element.offsetWidth > 0 &&
- element.offsetHeight > 0 &&
- window.getComputedStyle(element).visibility !== 'hidden' &&
- window.getComputedStyle(element).display !== 'none';
-
- if (!isVisible) continue;
-
- const rect = element.getBoundingClientRect();
- const points = [
- {x: rect.left + rect.width * 0.25, y: rect.top + rect.height * 0.25},
- {x: rect.left + rect.width * 0.75, y: rect.top + rect.height * 0.25},
- {x: rect.left + rect.width * 0.25, y: rect.top + rect.height * 0.75},
- {x: rect.left + rect.width * 0.75, y: rect.top + rect.height * 0.75},
- {x: rect.left + rect.width / 2, y: rect.top + rect.height / 2}
- ];
-
- const isTopElement = points.some(point => {
- const topEl = document.elementFromPoint(point.x, point.y);
- let current = topEl;
- while (current && current !== document.body) {
- if (current === element) return true;
- current = current.parentElement;
- }
- return false;
- });
-
- if (isTopElement) {
- results[xpath] = {
- xpath: xpath,
- isVisible: true,
- isTopElement: true
- };
- }
- }
- return results;
- })();
- """ % json.dumps({xpath: {} for xpath in elements.keys()})
+ def process_node(node: DOMBaseNode):
+ if isinstance(node, DOMElementNode):
+ if node.highlight_index is not None:
+ selector_map[node.highlight_index] = node
- try:
- results = await self.page.evaluate(check_script)
- return BatchCheckResults(
- elements={xpath: ElementCheckResult(**data) for xpath, data in results.items()},
- texts={},
- )
- except Exception as e:
- logger.error('Error in batch element check: %s', e)
- return BatchCheckResults(elements={}, texts={})
+ for child in node.children:
+ process_node(child)
- async def _batch_check_texts(
- self, texts: dict[str, tuple[NavigableString, int]]
- ) -> BatchCheckResults:
- if not texts:
- return BatchCheckResults(elements={}, texts={})
+ process_node(element_tree)
+ return selector_map
- check_script = """
- (function() {
- const results = {};
- const texts = %s;
-
- for (const [xpath, textData] of Object.entries(texts)) {
- const parent = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
- if (!parent) continue;
-
- try {
- const range = document.createRange();
- const textNode = parent.childNodes[textData.index];
- range.selectNodeContents(textNode);
- const rect = range.getBoundingClientRect();
-
- const isVisible = (
- rect.width !== 0 &&
- rect.height !== 0 &&
- rect.top >= 0 &&
- rect.top <= window.innerHeight &&
- parent.checkVisibility({
- checkOpacity: true,
- checkVisibilityCSS: true
- })
- );
-
- if (isVisible) {
- results[xpath] = {
- xpath: xpath,
- isVisible: true
- };
- }
- } catch (e) {
- continue;
- }
- }
- return results;
- })();
- """ % json.dumps(
- {
- xpath: {'index': list(text_node[0].parent.children).index(text_node[0])}
- for xpath, text_node in texts.items()
- if text_node[0].parent
- }
- )
+ def _parse_node(
+ self, node_data: dict, parent: Optional[DOMElementNode] = None
+ ) -> Optional[DOMBaseNode]:
+ if not node_data:
+ return None
- try:
- results = await self.page.evaluate(check_script)
- return BatchCheckResults(
- elements={},
- texts={xpath: TextCheckResult(**data) for xpath, data in results.items()},
+ if node_data.get('type') == 'TEXT_NODE':
+ text_node = DOMTextNode(
+ text=node_data['text'],
+ is_visible=node_data['isVisible'],
+ parent=parent,
)
- except Exception as e:
- logger.error('Error in batch text check: %s', e)
- return BatchCheckResults(elements={}, texts={})
-
-
- def _extract_text_from_all_children(self, element: Tag) -> str:
- # Tell BeautifulSoup that button tags can contain content
- # if not hasattr(element.parser, 'BUTTON_TAGS'):
- # element.parser.BUTTON_TAGS = set()
-
- text_content = ''
- for child in element.descendants:
- if isinstance(child, NavigableString):
- current_child_text = child.strip()
- else:
- current_child_text = child.get_text(strip=True)
-
- text_content += '\n' + current_child_text
- return text_content.strip() or ''
-
- def _is_interactive_element(self, element: Tag) -> bool:
- """Check if element is interactive based on tag name and attributes."""
- interactive_elements = {
- 'a',
- 'button',
- 'details',
- 'embed',
- 'input',
- 'label',
- 'menu',
- 'menuitem',
- 'object',
- 'select',
- 'textarea',
- 'summary',
- # 'dialog',
- # 'div',
- }
-
- interactive_roles = {
- 'button',
- 'menu',
- 'menuitem',
- 'link',
- 'checkbox',
- 'radio',
- 'slider',
- 'tab',
- 'tabpanel',
- 'textbox',
- 'combobox',
- 'grid',
- 'listbox',
- 'option',
- 'progressbar',
- 'scrollbar',
- 'searchbox',
- 'switch',
- 'tree',
- 'treeitem',
- 'spinbutton',
- 'tooltip',
- # 'dialog', # added
- # 'alertdialog', # added
- 'menuitemcheckbox',
- 'menuitemradio',
- }
-
- return (
- element.name in interactive_elements
- or element.get('role') in interactive_roles
- or element.get('aria-role') in interactive_roles
- or element.get('tabindex') == '0'
+ return text_node
+
+ element_node = DOMElementNode(
+ tag_name=node_data['tagName'],
+ xpath=node_data['xpath'],
+ attributes=node_data.get('attributes', {}),
+ children=[], # Initialize empty, will fill later
+ is_visible=node_data['isVisible'],
+ is_interactive=node_data['isInteractive'],
+ is_top_element=node_data['isTopElement'],
+ highlight_index=node_data.get('highlightIndex'),
+ iframe_context=node_data.get('iframeContext'),
+ shadow_root=node_data.get('shadowRoot', False),
+ parent=parent,
)
- def _is_leaf_element(self, element: Tag) -> bool:
- """Check if element is a leaf element."""
- if not element.get_text(strip=True):
- return False
-
- if not list(element.children):
- return True
-
- # Check for simple text-only elements
- children = list(element.children)
- if len(children) == 1 and isinstance(children[0], str):
- return True
-
- return False
-
- def _is_element_accepted(self, element: Tag) -> bool:
- """Check if element is accepted based on tag name and special cases."""
- leaf_element_deny_list = {'svg', 'script', 'style', 'link', 'meta'}
-
- # First check if it's in deny list
- if element.name in leaf_element_deny_list:
- return False
+ children: list[DOMBaseNode] = []
+ for child in node_data.get('children', []):
+ if child is not None:
+ child_node = self._parse_node(child, parent=element_node)
+ if child_node is not None:
+ children.append(child_node)
- return element.name not in leaf_element_deny_list
+ element_node.children = children
+ return element_node
diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.py
index 7b145cae5..c65dc3e30 100644
--- a/browser_use/dom/tests/extraction_test.py
+++ b/browser_use/dom/tests/extraction_test.py
@@ -3,14 +3,15 @@ import time
from tokencost import count_string_tokens
from browser_use.browser.service import Browser
+
+# from browser_use.browser.service import Browser
from browser_use.dom.service import DomService
from browser_use.utils import time_execution_sync
# @pytest.mark.skip("slow af")
async def test_process_html_file():
- browser = Browser(headless=True)
-
+ browser = Browser(headless=False)
page = await browser.get_current_page()
dom_service = DomService(page)
@@ -25,11 +26,14 @@ async def test_process_html_file():
# )
# browser._click_element_by_xpath("//button[div/div[text()='Alle akzeptieren']]")
- elements = await time_execution_sync('get_clickable_elements')(
+ dom_state = await time_execution_sync('get_clickable_elements')(
dom_service.get_clickable_elements
)()
+ elements = dom_state.element_tree
+ selector_map = dom_state.selector_map
- print(elements.dom_items_to_string(use_tabs=False))
- print('Tokens:', count_string_tokens(elements.dom_items_to_string(), model='gpt-4o'))
+ print(elements.clickable_elements_to_string(use_tabs=False))
+ print('Tokens:', count_string_tokens(elements.clickable_elements_to_string(), model='gpt-4o'))
+ print(len(selector_map.keys()), 'elements highlighted')
input('Press Enter to continue...')
diff --git a/browser_use/dom/tests/process_dom_test.py b/browser_use/dom/tests/process_dom_test.py
index d36d6bfdb..1661455fa 100644
--- a/browser_use/dom/tests/process_dom_test.py
+++ b/browser_use/dom/tests/process_dom_test.py
@@ -12,9 +12,9 @@ async def test_process_dom():
# dom_service = DomService(page)
- # await page.goto('https://kayak.com/flights')
- # browser.go_to_url('https://google.com/flights')
- await page.goto('https://immobilienscout24.de')
+ 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')
time.sleep(3)
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index a1c17f707..32c05bcea 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -1,53 +1,127 @@
-from typing import Dict, List
-from pydantic import BaseModel
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Dict, List, Optional
+# Avoid circular import issues
+if TYPE_CHECKING:
+ from .views import DOMElementNode
-class DomContentItem(BaseModel):
- index: int
- text: str
- is_text_only: bool
- depth: int
+
+@dataclass(frozen=False)
+class DOMBaseNode:
+ is_visible: bool
+ # Use None as default and set parent later to avoid circular reference issues
+ parent: Optional['DOMElementNode']
-SelectorMap = dict[int, str]
+@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:
+ if current.highlight_index is not None:
+ return True
+ current = current.parent
+ return False
-class ProcessedDomContent(BaseModel):
- items: list[DomContentItem]
- selector_map: SelectorMap
- def dom_items_to_string(self, use_tabs: bool = True) -> str:
+@dataclass(frozen=False)
+class DOMElementNode(DOMBaseNode):
+ tag_name: str
+ xpath: str
+ attributes: Dict[str, str]
+ children: List[DOMBaseNode]
+ is_interactive: bool = False
+ is_top_element: bool = False
+ iframe_context: Optional[str] = None
+ shadow_root: bool = False
+ highlight_index: Optional[int] = None
+
+ def get_all_text_till_next_clickable_element(self) -> str:
+ text_parts = []
+
+ def collect_text(node: DOMBaseNode) -> None:
+ # 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
+
+ if isinstance(node, DOMTextNode):
+ text_parts.append(node.text)
+ elif isinstance(node, DOMElementNode):
+ for child in node.children:
+ collect_text(child)
+
+ collect_text(self)
+ return '\n'.join(text_parts).strip()
+
+ def clickable_elements_to_string(self, use_tabs: bool = True) -> str:
"""Convert the processed DOM content to HTML."""
- formatted_text = ''
- for item in self.items:
- item_depth = '\t' * item.depth * 1 if use_tabs else ''
- if item.is_text_only:
- formatted_text += f'_[:]{item_depth}{item.text}\n'
- else:
- formatted_text += f'{item.index}[:]{item_depth}{item.text}\n'
- return formatted_text
+ formatted_text = []
+ def process_node(node: DOMBaseNode, depth: int) -> None:
+ indent = '\t' * depth if use_tabs else ''
-class ElementState(BaseModel):
- isVisible: bool
- isTopElement: bool
+ if isinstance(node, DOMElementNode):
+ # Add element with highlight_index
+ if node.highlight_index is not None:
+ formatted_text.append(
+ f'{node.highlight_index}[:]{indent}<{node.tag_name}>{node.get_all_text_till_next_clickable_element()}</{node.tag_name}>'
+ )
+ # Process children regardless
+ for child in node.children:
+ process_node(child, depth + 1)
-class TextState(BaseModel):
- isVisible: bool
+ elif isinstance(node, DOMTextNode):
+ # Add text only if it doesn't have a highlighted parent
+ if not node.has_parent_with_highlight_index():
+ formatted_text.append(f'_[:]{indent}{node.text}')
+ process_node(self, 0)
+ return '\n'.join(formatted_text)
-class ElementCheckResult(BaseModel):
- xpath: str
- isVisible: bool
- isTopElement: bool
+class ElementTreeSerializer:
+ @staticmethod
+ def serialize_clickable_elements(element_tree: DOMElementNode) -> str:
+ return element_tree.clickable_elements_to_string()
-class TextCheckResult(BaseModel):
- xpath: str
- isVisible: bool
+ # def reconstruct_html_from_clickable_elements(self, element_tree: ElementNode) -> str:
+ # """Convert the clickable elements back into HTML format."""
+ # html_parts = []
+ # def process_node(node: BaseNode) -> None:
+ # if isinstance(node, ElementNode):
+ # # Start tag
+ # attributes = ' '.join(f'{k}="{v}"' for k, v in node.attributes.items())
+ # tag_start = f'<{node.tag_name}'
+ # if attributes:
+ # tag_start += f' {attributes}'
+ # html_parts.append(f'{tag_start}>')
-class BatchCheckResults(BaseModel):
- elements: Dict[str, ElementCheckResult]
- texts: Dict[str, TextCheckResult]
+ # # Process children
+ # for child in node.children:
+ # process_node(child)
+
+ # # End tag
+ # html_parts.append(f'</{node.tag_name}>')
+ # elif isinstance(node, TextNode) and node.is_visible:
+ # html_parts.append(node.text)
+
+ # process_node(element_tree)
+ # return ''.join(html_parts)
+
+
+SelectorMap = dict[int, DOMElementNode]
+
+
+@dataclass
+class DOMState:
+ element_tree: DOMElementNode
+ selector_map: SelectorMap