Skip to content

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

Fix xPath generation

magmuellerb44d81b791b6
diff --git a/src/agent/prompts.py b/src/agent/prompts.py
index cefb2b110..4e6b41ad0 100644
--- a/src/agent/prompts.py
+++ b/src/agent/prompts.py
@@ -45,6 +45,7 @@ class AgentSystemPrompt:
{self.default_action_description}
To interact with elements, use their index number in the click_element() or input_text() actions.
+ Make sure to only use indexes that are present in the list.
If you need more text from the page you can use the extract_page_content action.
If you get stuck and multiple time dont achieve the next_goal, try to find a new element that can help you achieve your task or if persistent, go back or reload the page and try a different approach.
@@ -85,5 +86,6 @@ Interactive elements:
return HumanMessage(content=state_description)
+ @time_execution_sync('get_message_for_history')
def get_message_for_history(self) -> HumanMessage:
return HumanMessage(content=f'Currently on url: {self.state.url}')
diff --git a/src/agent/service.py b/src/agent/service.py
index 3d9804139..75909616c 100644
--- a/src/agent/service.py
+++ b/src/agent/service.py
@@ -8,7 +8,7 @@ from src.agent.prompts import AgentMessagePrompt, AgentSystemPrompt
from src.agent.views import AgentOutput, Output
from src.controller.service import ControllerService
from src.controller.views import ControllerActionResult, ControllerPageState
-from src.utils import time_execution_async
+from src.utils import time_execution_async, time_execution_sync
load_dotenv()
@@ -143,6 +143,7 @@ class AgentService:
def _get_action_description(self) -> str:
return AgentOutput.description()
+ @time_execution_sync('_save_conversation')
def _save_conversation(self, input_messages: list[BaseMessage], response: Output):
if self.save_file is not None:
with open(self.save_file + f'_{self.n}.txt', 'w') as f:
diff --git a/src/controller/service.py b/src/controller/service.py
index 63fa267bc..7062af5dd 100644
--- a/src/controller/service.py
+++ b/src/controller/service.py
@@ -21,11 +21,12 @@ class ControllerService:
self.cached_browser_state: BrowserState | None = None
def get_cached_browser_state(self, force_update: bool = False) -> BrowserState:
- if self.cached_browser_state is None or force_update:
- self.cached_browser_state = self.browser.get_updated_state()
- return self.cached_browser_state
+ # if self.cached_browser_state is None or force_update:
+ # self.cached_browser_state = self.browser.get_updated_state()
+ # return self.cached_browser_state
- return self.cached_browser_state
+ # return self.cached_browser_state
+ return self.browser.get_updated_state()
def get_current_state(self, screenshot: bool = False) -> ControllerPageState:
browser_state = self.get_cached_browser_state(force_update=True)
@@ -45,7 +46,7 @@ class ControllerService:
@time_execution_sync('act')
def act(self, action: ControllerActions) -> ControllerActionResult:
try:
- current_state = self.get_cached_browser_state(force_update=True)
+ current_state = self.get_cached_browser_state(force_update=False)
if action.search_google:
self.browser.search_google(action.search_google.query)
diff --git a/src/dom/service.py b/src/dom/service.py
index 07a129ea4..0068aefce 100644
--- a/src/dom/service.py
+++ b/src/dom/service.py
@@ -1,5 +1,6 @@
from bs4 import BeautifulSoup, NavigableString, PageElement, Tag
from selenium import webdriver
+from selenium.webdriver.common.by import By
from src.dom.views import DomContentItem, ProcessedDomContent
@@ -7,10 +8,10 @@ from src.dom.views import DomContentItem, ProcessedDomContent
class DomService:
def __init__(self, driver: webdriver.Chrome):
self.driver = driver
+ self.xpath_cache = {} # Add cache at instance level
def get_clickable_elements(self) -> ProcessedDomContent:
# Clear xpath cache on each new DOM processing
- self.xpath_cache = {}
html_content = self.driver.page_source
return self._process_content(html_content)
@@ -25,12 +26,12 @@ class DomService:
@dev TODO: instead of of using enumerated index, use random 4 digit numbers -> a bit more tokens BUT updates on the screen wont click on incorrect items -> tricky because you have to consider that same elements need to have the same index ...
"""
- # Parse HTML content using BeautifulSoup
- soup = BeautifulSoup(html_content, 'lxml')
+ # Parse HTML content using BeautifulSoup with html.parser
+ 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 = {}
+ # xpath_cache = {}
# Find candidate elements
while dom_queue:
@@ -76,10 +77,10 @@ class DomService:
output_items: list[DomContentItem] = []
for index, element in enumerate(candidate_elements):
- xpath = xpath_cache.get(element)
- if not xpath:
- xpath = self._generate_xpath(element)
- xpath_cache[element] = xpath
+ # xpath = xpath_cache.get(element)
+ # if not xpath:
+ xpath = self._generate_xpath(element)
+ # xpath_cache[element] = xpath
# Skip text nodes that are direct children of already processed elements
if isinstance(element, NavigableString) and element.parent in [
@@ -218,60 +219,73 @@ class DomService:
return element.name not in leaf_element_deny_list
def _generate_xpath(self, element: Tag | NavigableString) -> str:
- """Generate XPath for given element."""
- # Handle NavigableString - return parent's xpath
+ # Generate cache key based on element properties
+ cache_key = None
+ if isinstance(element, Tag):
+ attributes = [
+ element.get('id', ''),
+ element.get('class', ''),
+ element.name,
+ element.get_text().strip(),
+ ]
+ cache_key = '|'.join(str(attr) for attr in attributes)
+
+ # Return cached xpath if exists
+ if cache_key in self.xpath_cache:
+ return self.xpath_cache[cache_key]
+
if isinstance(element, NavigableString):
if element.parent:
return self._generate_xpath(element.parent)
return ''
- # Handle elements that may not have all Tag methods
if not hasattr(element, 'name'):
return ''
- # Check for ID using getattr to handle elements without get() method
element_id = getattr(element, 'get', lambda x: None)('id')
if element_id:
- return f"//*[@id='{element_id}']"
+ xpath = f"//*[@id='{element_id}']"
+ if cache_key:
+ self.xpath_cache[cache_key] = xpath
+ return xpath
parts = []
current = element
while current and getattr(current, 'name', None):
- # Skip document node
if current.name == '[document]':
break
- # Safely get parent and children
parent = getattr(current, 'parent', None)
- siblings = list(parent.children) if parent and hasattr(parent, 'children') else []
-
- # Filter siblings that are elements with matching names
- same_type_siblings = [
- s for s in siblings if hasattr(s, 'name') and s.name == current.name
- ]
-
- if len(same_type_siblings) > 1:
- try:
- index = same_type_siblings.index(current) + 1
- # print(
- # f'Debug XPath: Found {len(same_type_siblings)} siblings of type {current.name}, current index: {index}'
- # )
- parts.insert(0, f'{current.name}[{index}]')
- except ValueError:
+ if parent and hasattr(parent, 'children'):
+ # Get only visible element nodes
+ siblings = [
+ s for s in parent.find_all(current.name, recursive=False) if isinstance(s, Tag)
+ ]
+
+ if len(siblings) > 1:
+ try:
+ index = siblings.index(current) + 1
+ parts.insert(0, f'{current.name}[{index}]')
+ except ValueError:
+ parts.insert(0, current.name)
+ else:
parts.insert(0, current.name)
- else:
- parts.insert(0, current.name)
current = parent
- # Ensure we start with html and body tags for a complete path
if parts and parts[0] != 'html':
parts.insert(0, 'html')
if len(parts) > 1 and parts[1] != 'body':
parts.insert(1, 'body')
- return '//' + '/'.join(parts) if parts else ''
+ xpath = '//' + '/'.join(parts)
+
+ # Cache the generated xpath
+ if cache_key:
+ self.xpath_cache[cache_key] = xpath
+
+ return xpath
def _get_essential_attributes(self, element: Tag) -> str:
"""
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 408572d3a..b0284f82b 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -67,6 +67,7 @@ async def test_kayak_flight_search():
# print('action:\n', action)
print('result:\n', result.model_dump_json(indent=4))
+ input('Press Enter to continue...')
# current_state = agent.get_current_state()
# save_formatted_html(