Skip to content

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

preserve element structure in outputs

Gregor Žunič7c5bc97e15f2
diff --git a/README.md b/README.md
index 027586f02..4b1430ef7 100644
--- a/README.md
+++ b/README.md
@@ -65,8 +65,8 @@ await agent.run()
1. Create a virtual environment and install dependencies:
```bash
-# I recommend using uv
-pip install .
+# To install all dependencies including dev
+pip install . ."[dev]"
```
2. Add your API keys to the `.env` file:
@@ -74,7 +74,9 @@ pip install .
```bash
cp .env.example .env
```
+
E.g. for OpenAI:
+
```bash
OPENAI_API_KEY=
```
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 7097f2fa8..f064c72fe 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -25,8 +25,10 @@ class AgentSystemPrompt:
Your input are all the interactive elements with its context of the current page from.
This is how an input looks like:
- 33: <button>Clickable element</button>
+ 33:\t<button>Clickable element</button>
_: Not clickable, only for your context
+ \t: Tab indent (1 tab for depth 1 etc.). This is to help you understand which elements belong to each other.
+
In the beginning the list will be empty.
On elements with _ you can not click.
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index c111ce312..c3ff65a05 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -38,31 +38,21 @@ class DomService:
soup = BeautifulSoup(html_content, 'html.parser')
candidate_elements: list[Tag | NavigableString] = []
- dom_queue = [element for element in soup.body.children] if soup.body else []
- # xpath_cache = {}
- # Find candidate elements
- while dom_queue:
- element = dom_queue.pop()
+ def _process_element(element: PageElement):
should_add_element = False
- # Add quick filter before expensive checks
- if not self._quick_element_filter(element):
- if isinstance(element, Tag):
- element.decompose()
- continue
+ # if not self._quick_element_filter(element):
+ # if isinstance(element, Tag):
+ # element.decompose()
+ # return
- # Handle both Tag elements and text nodes
if isinstance(element, Tag):
+ # Don't add any children of non-interactive elements
if not self._is_element_accepted(element):
- # Skip element if it's not accepted
- element.decompose() # get rid of some memory leaks potentially
- continue
-
- for child in element.children:
- dom_queue.append(child)
+ element.decompose()
+ return
- # Check if element is interactive or leaf element
if self._is_interactive_element(element) or self._is_leaf_element(element):
if (
self._is_active(element)
@@ -71,14 +61,20 @@ class DomService:
):
should_add_element = True
- elif isinstance(element, NavigableString) and element.strip():
- if self._is_visible(element):
- should_add_element = True
+ elif isinstance(element, NavigableString) and element.strip():
+ if self._is_visible(element):
+ should_add_element = True
if should_add_element:
- if not isinstance(element, (Tag, NavigableString)):
- continue
- candidate_elements.append(element)
+ if isinstance(element, (Tag, NavigableString)):
+ candidate_elements.append(element)
+
+ if isinstance(element, Tag):
+ for child in element.children:
+ _process_element(child)
+
+ for element in soup.body.children if soup.body else []:
+ _process_element(element)
# Process candidates
selector_map: dict[int, str] = {}
@@ -87,6 +83,8 @@ class DomService:
for index, element in enumerate(candidate_elements):
xpath = self._generate_xpath(element)
+ depth = max(len(xpath.split('/')) - 2, 0)
+
# Skip text nodes that are direct children of already processed elements
if isinstance(element, NavigableString) and element.parent in [
e for e in candidate_elements
@@ -98,7 +96,9 @@ class DomService:
if text_content:
output_string = f'{text_content}'
output_items.append(
- DomContentItem(index=index, text=output_string, clickable=False)
+ DomContentItem(
+ index=index, text=output_string, clickable=False, depth=depth
+ )
)
continue
else:
@@ -115,7 +115,9 @@ class DomService:
closing_tag = f'</{tag_name}>'
output_string = f'{opening_tag}{text_content}{closing_tag}'
- output_items.append(DomContentItem(index=index, text=output_string, clickable=True))
+ output_items.append(
+ DomContentItem(index=index, text=output_string, clickable=True, depth=depth)
+ )
selector_map[index] = xpath
@@ -461,39 +463,39 @@ class DomService:
or element.get('aria-disabled') == 'true'
)
- def _quick_element_filter(self, element: PageElement) -> bool:
- """
- Quick pre-filter to eliminate elements before expensive checks.
- Returns True if element passes initial filtering.
- """
- if isinstance(element, NavigableString):
- # Quick check for empty or whitespace-only strings
- return bool(element.strip())
-
- if not isinstance(element, Tag):
- return False
-
- style = element.get('style')
-
- # Quick attribute checks that would make element invisible/non-interactive
- if any(
- [
- element.get('aria-hidden') == 'true',
- element.get('hidden') is not None,
- element.get('disabled') is not None,
- style and ('display: none' in style or 'visibility: hidden' in style),
- element.has_attr('class')
- and any(cls in element['class'] for cls in ['hidden', 'invisible']),
- # Common hidden class patterns
- element.get('type') == 'hidden',
- ]
- ):
- return False
-
- # Skip elements that definitely won't be interactive or visible
- non_interactive_display = ['none', 'hidden']
- computed_style = element.get('style', '') or ''
- if any(display in computed_style for display in non_interactive_display):
- return False
-
- return True
+ # def _quick_element_filter(self, element: PageElement) -> bool:
+ # """
+ # Quick pre-filter to eliminate elements before expensive checks.
+ # Returns True if element passes initial filtering.
+ # """
+ # if isinstance(element, NavigableString):
+ # # Quick check for empty or whitespace-only strings
+ # return bool(element.strip())
+
+ # if not isinstance(element, Tag):
+ # return False
+
+ # style = element.get('style')
+
+ # # Quick attribute checks that would make element invisible/non-interactive
+ # if any(
+ # [
+ # element.get('aria-hidden') == 'true',
+ # element.get('hidden') is not None,
+ # element.get('disabled') is not None,
+ # style and ('display: none' in style or 'visibility: hidden' in style),
+ # element.has_attr('class')
+ # and any(cls in element['class'] for cls in ['hidden', 'invisible']),
+ # # Common hidden class patterns
+ # element.get('type') == 'hidden',
+ # ]
+ # ):
+ # return False
+
+ # # Skip elements that definitely won't be interactive or visible
+ # non_interactive_display = ['none', 'hidden']
+ # computed_style = element.get('style', '') or ''
+ # if any(display in computed_style for display in non_interactive_display):
+ # return False
+
+ # return True
diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.py
index 94154f676..317dd02ba 100644
--- a/browser_use/dom/tests/extraction_test.py
+++ b/browser_use/dom/tests/extraction_test.py
@@ -1,5 +1,9 @@
import time
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from tokencost import count_string_tokens
+
from browser_use.browser.service import BrowserService
from browser_use.dom.service import DomService
from browser_use.utils import time_execution_sync
@@ -14,11 +18,19 @@ def test_process_html_file():
dom_service = DomService(driver)
browser.go_to_url('https://www.kayak.ch')
+ # browser.go_to_url('https://google.com/flights')
- time.sleep(3)
+ time.sleep(1)
+ # browser._click_element_by_xpath(
+ # '/html/body/div[5]/div/div[2]/div/div/div[3]/div/div[1]/button[1]'
+ # )
+ browser._click_element_by_xpath("//button[div/div[text()='Alle akzeptieren']]")
elements = time_execution_sync('get_clickable_elements')(
dom_service.get_clickable_elements().dom_items_to_string
)()
print(elements)
+ print('Tokens:', count_string_tokens(elements, model='gpt-4o'))
+
+ input('Press Enter to continue...')
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 9933c381d..2abaa098d 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -5,6 +5,7 @@ class DomContentItem(BaseModel):
index: int
text: str
clickable: bool
+ depth: int
class ProcessedDomContent(BaseModel):
@@ -15,8 +16,9 @@ class ProcessedDomContent(BaseModel):
"""Convert the processed DOM content to HTML."""
formatted_text = ''
for item in self.items:
+ item_depth = '\t' * item.depth * 1
if item.clickable:
- formatted_text += f'{item.index}:{item.text}\n'
+ formatted_text += f'{item.index}:{item_depth}{item.text}\n'
else:
- formatted_text += f'_:{item.text}\n'
+ formatted_text += f'{item.index}:{item_depth}{item.text}\n'
return formatted_text
diff --git a/pyproject.toml b/pyproject.toml
index 06948b131..717376d81 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -40,4 +40,10 @@ docstring-code-format = true
[build-system]
requires = ["hatchling"]
-build-backend = "hatchling.build"
\ No newline at end of file
+build-backend = "hatchling.build"
+
+[project.optional-dependencies]
+dev = [
+ "tokencost>=0.1.16",
+ "hatch>=1.13.0",
+]