Skip to content

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

added highlighting of items

Gregor Žuničf11c37388d4a
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 716942646..d25f17840 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -14,7 +14,10 @@ from browser_use.agent.views import (
Output,
)
from browser_use.controller.service import ControllerService
-from browser_use.controller.views import ControllerActionResult, ControllerActions, ControllerPageState
+from browser_use.controller.views import (
+ ControllerActionResult,
+ ControllerPageState,
+)
from browser_use.utils import time_execution_async
load_dotenv()
diff --git a/browser_use/browser/service.py b/browser_use/browser/service.py
index 543e4fdc8..a05a08141 100644
--- a/browser_use/browser/service.py
+++ b/browser_use/browser/service.py
@@ -22,6 +22,7 @@ from webdriver_manager.chrome import ChromeDriverManager
from browser_use.browser.views import BrowserState
from browser_use.dom.service import DomService
+from browser_use.dom.views import SelectorMap
from browser_use.utils import time_execution_sync
logger = logging.getLogger(__name__)
@@ -211,11 +212,15 @@ class BrowserService:
logger.info(f'Done on page {self.current_state.url}\n\n: {text}')
return text
- def take_screenshot(self, full_page: bool = False) -> str:
+ def take_screenshot(self, selector_map: SelectorMap | None, full_page: bool = False) -> str:
"""
Returns a base64 encoded screenshot of the current page.
"""
driver = self._get_driver()
+
+ if selector_map:
+ self.highlight_selector_map_elements(selector_map)
+
if full_page:
# Create temp directory
temp_dir = tempfile.mkdtemp()
@@ -236,8 +241,74 @@ class BrowserService:
os.rmdir(temp_dir)
else:
screenshot = driver.get_screenshot_as_base64()
+
+ if selector_map:
+ self.remove_highlights()
+
return screenshot
+ def highlight_selector_map_elements(self, selector_map: SelectorMap):
+ driver = self._get_driver()
+ # First remove any existing highlights/labels
+ self.remove_highlights()
+
+ script = """
+ const highlights = {
+ """
+
+ # Build the highlights object with all xpaths and indices
+ for index, xpath in selector_map.items():
+ script += f'"{index}": "{xpath}",\n'
+
+ script += """
+ };
+
+ for (const [index, xpath] of Object.entries(highlights)) {
+ const el = document.evaluate(xpath, 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', 'selenium-highlight');
+
+ const label = document.createElement("div");
+ label.className = 'selenium-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);
+ }
+ """
+
+ driver.execute_script(script)
+
+ def remove_highlights(self):
+ """
+ Removes all highlight outlines and labels created by highlight_selector_map_elements
+ """
+ driver = self._get_driver()
+ driver.execute_script(
+ """
+ // Remove all highlight outlines
+ const highlightedElements = document.querySelectorAll('[browser-user-highlight-id="selenium-highlight"]');
+ highlightedElements.forEach(el => {
+ el.style.outline = '';
+ el.removeAttribute('selenium-browser-use-highlight');
+ });
+
+
+ // Remove all labels
+ const labels = document.querySelectorAll('.selenium-highlight-label');
+ labels.forEach(label => label.remove());
+ """
+ )
+
# endregion
# region - User Actions
diff --git a/browser_use/browser/tests/highlight_elements.py b/browser_use/browser/tests/highlight_elements.py
new file mode 100644
index 000000000..e9b7f3d17
--- /dev/null
+++ b/browser_use/browser/tests/highlight_elements.py
@@ -0,0 +1,36 @@
+import time
+
+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
+
+
+def test_highlight_elements():
+ browser = BrowserService(headless=False)
+
+ driver = browser.init()
+
+ dom_service = DomService(driver)
+
+ browser.go_to_url('https://www.kayak.ch')
+ # browser.go_to_url('https://google.com/flights')
+
+ 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)()
+
+ time_execution_sync('highlight_selector_map_elements')(browser.highlight_selector_map_elements)(
+ elements.selector_map
+ )
+
+ input('Press Enter to continue...')
+
+ time_execution_sync('remove_highlights')(browser.remove_highlights)()
+
+ input('Press Enter to continue...')
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index e437a6d92..807aafdc7 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -1,8 +1,16 @@
+import logging
from browser_use.browser.service import BrowserService
from browser_use.browser.views import BrowserState
-from browser_use.controller.views import ControllerActionResult, ControllerActions, ControllerPageState
+from browser_use.controller.views import (
+ ControllerActionResult,
+ ControllerActions,
+ ControllerPageState,
+)
from browser_use.utils import time_execution_sync
+logger = logging.getLogger(__name__)
+logging.basicConfig(level=logging.INFO)
+
class ControllerService:
"""
@@ -37,7 +45,7 @@ class ControllerService:
screenshot_b64 = None
if screenshot:
- screenshot_b64 = self.browser.take_screenshot()
+ screenshot_b64 = self.browser.take_screenshot(selector_map=browser_state.selector_map)
return ControllerPageState(
items=browser_state.items,
diff --git a/browser_use/controller/tests/current_state.py b/browser_use/controller/tests/current_state.py
new file mode 100644
index 000000000..a550949a2
--- /dev/null
+++ b/browser_use/controller/tests/current_state.py
@@ -0,0 +1,15 @@
+import pytest
+from browser_use.controller.service import ControllerService
+
+
+def test_get_current_state():
+ # Initialize controller
+ controller = ControllerService()
+
+ # Go to a test URL
+ controller.browser.go_to_url('https://www.example.com')
+
+ # Get current state without screenshot
+ state = controller.get_current_state(screenshot=True)
+
+ input('Press Enter to continue...')
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index c3ff65a05..811eade49 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -121,6 +121,11 @@ class DomService:
selector_map[index] = xpath
+ # Remove all elements from selector map that are not in output items
+ selector_map = {
+ k: v for k, v in selector_map.items() if k in [i.index for i in output_items]
+ }
+
return ProcessedDomContent(items=output_items, selector_map=selector_map)
def _cap_text_length(self, text: str, max_length: int = 150) -> str:
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 2abaa098d..294b13368 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -8,9 +8,12 @@ class DomContentItem(BaseModel):
depth: int
+SelectorMap = dict[int, str]
+
+
class ProcessedDomContent(BaseModel):
items: list[DomContentItem]
- selector_map: dict[int, str]
+ selector_map: SelectorMap
def dom_items_to_string(self) -> str:
"""Convert the processed DOM content to HTML."""