Skip to content

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

making extraction simpler, removed some unnecesary optimizations

Gregor Žuničb1aa20ae6425
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 45a847e28..b9c546c86 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -85,7 +85,7 @@ class AgentMessagePrompt:
self.agent_history_description: str | None = agent_history_description
self.read_state_description: str | None = read_state_description
self.task: str | None = task
- self.include_attributes = include_attributes or []
+ self.include_attributes = include_attributes
self.step_info = step_info
self.page_filtered_actions: str | None = page_filtered_actions
self.max_clickable_elements_length: int = max_clickable_elements_length
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index d5120923e..745589652 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -21,6 +21,7 @@ from browser_use.agent.cloud_events import (
CreateAgentTaskEvent,
UpdateAgentTaskEvent,
)
+from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import BaseMessage, UserMessage
from browser_use.tokens.service import TokenCost
@@ -152,21 +153,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
message_context: str | None = None,
generate_gif: bool | str = False,
available_file_paths: list[str] | None = None,
- include_attributes: list[str] = [
- 'title',
- 'type',
- 'name',
- 'role',
- 'aria-label',
- 'placeholder',
- 'value',
- 'alt',
- 'aria-expanded',
- 'data-date-format',
- 'checked',
- 'data-state',
- 'aria-checked',
- ],
+ include_attributes: list[str] = DEFAULT_INCLUDE_ATTRIBUTES,
max_actions_per_step: int = 10,
use_thinking: bool = True,
page_extraction_llm: BaseChatModel | None = None,
diff --git a/browser_use/dom/dom_tree/index.js b/browser_use/dom/dom_tree/index.js
index d98959535..56d212034 100644
--- a/browser_use/dom/dom_tree/index.js
+++ b/browser_use/dom/dom_tree/index.js
@@ -647,6 +647,8 @@
return true;
}
+ // return false
+
const interactiveRoles = new Set([
'button', // Directly clickable element
// 'link', // Clickable link
@@ -667,6 +669,8 @@
'scrollbar' // Scrollable control
]);
+ // return false
+
// Basic role/attribute checks
const hasInteractiveRole =
interactiveElements.has(tagName) ||
@@ -675,6 +679,8 @@
if (hasInteractiveRole) return true;
+ return false
+
// check whether element has event listeners by window.getEventListeners
try {
if (typeof getEventListeners === 'function') {
@@ -893,47 +899,6 @@
'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.
- */
- 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
@@ -973,6 +938,8 @@
return true;
}
+ // return false
+
// Check for other common interaction event listeners
try {
const getEventListenersForNode = element?.ownerDocument?.defaultView?.getEventListenersForNode || window.getEventListenersForNode;
@@ -997,10 +964,13 @@
// 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;
- }
+ // REMOVING THIS FOR NOW. It yields way too many false positives.
+ // 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.
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.py
index 42a14a479..aa2028589 100644
--- a/browser_use/dom/playground/extraction.py
+++ b/browser_use/dom/playground/extraction.py
@@ -1,4 +1,5 @@
import asyncio
+import json
import os
import time
@@ -7,30 +8,19 @@ 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
-DEFAULT_INCLUDE_ATTRIBUTES = [
- 'id',
- 'title',
- 'type',
- 'name',
- 'role',
- 'aria-label',
- 'placeholder',
- 'value',
- 'alt',
- 'aria-expanded',
- 'data-date-format',
-]
-
async def test_focus_vs_all_elements():
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,
@@ -90,21 +80,31 @@ async def test_focus_vs_all_elements():
include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,
step_info=None,
)
- # print(prompt.get_user_message(use_vision=False).content)
+ print(prompt.get_user_message(use_vision=False).content)
# 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:
- if isinstance(user_message, str):
- await f.write(user_message)
- else:
- await f.write(str(user_message))
+ 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=2))
+
+ # copy the user message to the clipboard
+ # pyperclip.copy(text_to_save)
encoding = tiktoken.encoding_for_model('gpt-4o')
- token_count = len(encoding.encode(user_message))
+ 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:
diff --git a/browser_use/dom/utils.py b/browser_use/dom/utils.py
new file mode 100644
index 000000000..0485a0ea0
--- /dev/null
+++ b/browser_use/dom/utils.py
@@ -0,0 +1,4 @@
+def cap_text_length(text: str, max_length: int) -> str:
+ if len(text) > max_length:
+ return text[:max_length] + '...'
+ return text
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 0964f37cc..3c04220bc 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -3,6 +3,7 @@ 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
@@ -52,6 +53,23 @@ class DOMTextNode(DOMBaseNode):
}
+DEFAULT_INCLUDE_ATTRIBUTES = [
+ 'title',
+ 'type',
+ # 'name',
+ 'role',
+ 'value',
+ 'aria-label',
+ 'placeholder',
+ 'alt',
+ 'aria-expanded',
+ 'data-date-format',
+ 'checked',
+ 'data-state',
+ 'aria-checked',
+]
+
+
@dataclass(frozen=False)
class DOMElementNode(DOMBaseNode):
"""
@@ -154,6 +172,9 @@ class DOMElementNode(DOMBaseNode):
"""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'
@@ -163,13 +184,39 @@ class DOMElementNode(DOMBaseNode):
if node.highlight_index is not None:
next_depth += 1
- text = node.get_all_text_till_next_clickable_element(max_depth=1)
- attributes_html_str = ''
+ text = node.get_all_text_till_next_clickable_element()
+ attributes_html_str = None
if include_attributes:
attributes_to_include = {
- key: str(value) for key, value in node.attributes.items() if key in include_attributes
+ key: str(value)
+ 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'):
@@ -189,9 +236,11 @@ class DOMElementNode(DOMBaseNode):
):
del attributes_to_include['placeholder']
- if attributes_to_include:
+ if attributes_to_include.items():
# Format as key1='value1' key2='value2'
- attributes_html_str = ' '.join(f"{key}='{value}'" for key, value in attributes_to_include.items())
+ 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:
@@ -206,6 +255,7 @@ class DOMElementNode(DOMBaseNode):
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}'