Skip to content

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

Optimized click

magmueller5afb32804b09
diff --git a/src/browser/service.py b/src/browser/service.py
index b9a529fc6..b8fc5a73c 100644
--- a/src/browser/service.py
+++ b/src/browser/service.py
@@ -127,7 +127,6 @@ class BrowserService:
if remaining > 0:
time.sleep(remaining)
- @time_execution_sync('get_updated_state')
def get_updated_state(self) -> BrowserState:
"""
Update and return state.
@@ -263,59 +262,51 @@ class BrowserService:
def _click_element_by_xpath(self, xpath: str):
"""
- Internal method to click an element using its xpath with improved element finding strategies.
+ Optimized method to click an element using xpath.
"""
driver = self._get_driver()
wait = self._webdriver_wait()
- # Wait for any overlays/popups to disappear
- # time.sleep(0.5) # Brief wait for page to stabilize
-
try:
- # Try multiple strategies to find the element
- for strategy in [
- lambda: wait.until(EC.element_to_be_clickable((By.XPATH, xpath))),
- lambda: wait.until(EC.presence_of_element_located((By.XPATH, xpath))),
- lambda: driver.find_element(By.XPATH, xpath),
- # Try with simplified XPath
- lambda: wait.until(
- EC.element_to_be_clickable(
- (
- By.XPATH,
- f"//*[@id='{xpath.split('id=')[-1].split(']')[0]}']"
- if 'id=' in xpath
- else xpath,
- )
- )
- ),
- # Try finding by any visible matching element
- lambda: next(
- elem
- for elem in driver.find_elements(
- By.XPATH, "//*[not(ancestor-or-self::*[@style='display: none'])]"
- )
- if elem.is_displayed() and elem.is_enabled()
- ),
- ]:
- try:
- element = strategy()
- if element and element.is_displayed() and element.is_enabled():
- # Scroll element into view using ActionChains for smoother scrolling
- actions = ActionChains(driver)
- actions.move_to_element(element).perform()
-
- # Try both JavaScript click and regular click
- try:
- driver.execute_script('arguments[0].click();', element)
- except Exception:
- element.click()
- finally:
- self.wait_for_page_load()
+ # First try the direct approach with a shorter timeout
+ try:
+ element = wait.until(
+ EC.element_to_be_clickable((By.XPATH, xpath)),
+ message=f'Element not clickable: {xpath}',
+ )
+ driver.execute_script('arguments[0].click();', element)
+ self.wait_for_page_load()
+ return
+ except Exception:
+ pass
+
+ # If that fails, try a simplified approach
+ try:
+ # Try with ID if present in xpath
+ if 'id=' in xpath:
+ id_value = xpath.split('id=')[-1].split(']')[0]
+ element = driver.find_element(By.ID, id_value)
+ if element.is_displayed() and element.is_enabled():
+ driver.execute_script('arguments[0].click();', element)
+ self.wait_for_page_load()
return
- except Exception:
- continue
-
- raise Exception(f'Could not find clickable element with xpath: {xpath}')
+ except Exception:
+ pass
+
+ # Last resort: force click with JavaScript
+ try:
+ element = driver.find_element(By.XPATH, xpath)
+ driver.execute_script(
+ """
+ arguments[0].scrollIntoView({behavior: 'instant', block: 'center'});
+ arguments[0].click();
+ """,
+ element,
+ )
+ self.wait_for_page_load()
+ return
+ except Exception as e:
+ 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)}')
diff --git a/src/controller/service.py b/src/controller/service.py
index 7062af5dd..21f175777 100644
--- a/src/controller/service.py
+++ b/src/controller/service.py
@@ -20,17 +20,17 @@ class ControllerService:
self.browser = BrowserService()
self.cached_browser_state: BrowserState | None = None
+ @time_execution_sync('get_cached_browser_state')
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.browser.get_updated_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)
-
screenshot_b64 = None
if screenshot:
screenshot_b64 = self.browser.take_screenshot()
diff --git a/src/dom/service.py b/src/dom/service.py
index 0068aefce..f2674c746 100644
--- a/src/dom/service.py
+++ b/src/dom/service.py
@@ -12,6 +12,7 @@ class DomService:
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)
@@ -77,10 +78,7 @@ 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
# Skip text nodes that are direct children of already processed elements
if isinstance(element, NavigableString) and element.parent in [
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index b0284f82b..9a1fa926d 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -67,7 +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...')
+ # input('Press Enter to continue...')
# current_state = agent.get_current_state()
# save_formatted_html(