Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
added *[]* for elements newly app; fixes
Gregor Žuničbe0a3eb56480
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 69603e081..a124cdfde 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -388,7 +388,7 @@ class Agent(Generic[Context]):tokens = 0try:- state = await self.browser_context.get_state()+ state = await self.browser_context.get_state(cache_clickable_elements_hashes=True)active_page = await self.browser_context.get_current_page()# generate procedural memory if needed@@ -867,7 +867,7 @@ class Agent(Generic[Context]):for i, action in enumerate(actions):if action.get_index() is not None and i != 0:- new_state = await self.browser_context.get_state()+ new_state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)new_selector_map = new_state.selector_map# Detect index change after previous action@@ -934,7 +934,7 @@ class Agent(Generic[Context]):)if self.browser_context.session:- state = await self.browser_context.get_state()+ state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)content = AgentMessagePrompt(state=state,result=self.state.last_result,@@ -1041,7 +1041,7 @@ class Agent(Generic[Context]):async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> list[ActionResult]:"""Execute a single step from history with element validation"""- state = await self.browser_context.get_state()+ state = await self.browser_context.get_state(cache_clickable_elements_hashes=False)if not state or not history_item.model_output:raise ValueError('Invalid state or model output')updated_actions = []diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.mdindex fe2436487..35d507edc 100644--- a/browser_use/agent/system_prompt.md+++ b/browser_use/agent/system_prompt.md@@ -13,10 +13,12 @@ Interactive Elements- type: HTML element type (button, input, etc.)- text: Element descriptionExample:- [33]<button>Submit Form</button>+ [33]<div>User form</div>+ \t*[35]*<button aria-label='Submit form'>Submit</button>- Only elements with numeric indexes in [] are interactive-- (stacked) indentation is important and means that the element is a child of the element above (with a lower index)+- (stacked) indentation (with \t) is important and means that the element is a (html) child of the element above (with a lower index)+- Elements with \* are new elements that were added after the previous step (if url has not changed)# Response Rulesdiff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 16522d9c9..5d2f1e74d 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -32,6 +32,7 @@ from browser_use.browser.views import (TabInfo,URLNotAllowedError,)+from browser_use.dom.clickable_element_processor.service import ClickableElementProcessorfrom browser_use.dom.service import DomServicefrom browser_use.dom.views import DOMElementNode, SelectorMapfrom browser_use.utils import time_execution_async, time_execution_sync@@ -185,6 +186,16 @@ class BrowserContextConfig(BaseModel):timezone_id: str | None = None+@dataclass+class CachedStateClickableElementsHashes:+ """+ Clickable elements hashes for the last state+ """++ url: str+ hashes: set[str]++class BrowserSession:def __init__(self, context: PlaywrightBrowserContext, cached_state: BrowserState | None = None):init_script = """@@ -234,6 +245,9 @@ class BrowserSession:self.active_tab = Noneself.context = contextself.cached_state = cached_state++ self.cached_state_clickable_elements_hashes: CachedStateClickableElementsHashes | None = None+self.context.on('page', lambda page: page.add_init_script(init_script))@@ -878,11 +892,39 @@ class BrowserContext:return structure@time_execution_sync('--get_state') # This decorator might need to be updated to handle async- async def get_state(self) -> BrowserState:- """Get the current state of the browser"""+ async def get_state(self, cache_clickable_elements_hashes: bool) -> BrowserState:+ """Get the current state of the browser++ cache_clickable_elements_hashes: bool+ If True, cache the clickable elements hashes for the current state. This is used to calculate which elements are new to the llm (from last message) -> reduces token usage.+ """await self._wait_for_page_and_frames_load()session = await self.get_session()- session.cached_state = await self._update_state()+ updated_state = await self._get_updated_state()++ # Find out which elements are new+ # Do this only if url has not changed+ if cache_clickable_elements_hashes:+ # if we are on the same url as the last state, we can use the cached hashes+ if (+ session.cached_state_clickable_elements_hashes+ and session.cached_state_clickable_elements_hashes.url == updated_state.url+ ):+ # Pointers, feel free to edit in place+ updated_state_clickable_elements = ClickableElementProcessor.get_clickable_elements(updated_state.element_tree)++ for dom_element in updated_state_clickable_elements:+ dom_element.is_new = (+ ClickableElementProcessor.hash_dom_element(dom_element)+ not in session.cached_state_clickable_elements_hashes.hashes # see which elements are new from the last state where we cached the hashes+ )+ # in any case, we need to cache the new hashes+ session.cached_state_clickable_elements_hashes = CachedStateClickableElementsHashes(+ url=updated_state.url,+ hashes=ClickableElementProcessor.get_clickable_elements_hashes(updated_state.element_tree),+ )++ session.cached_state = updated_state# Save cookies if a file is specifiedif self.config.cookies_file:@@ -890,7 +932,7 @@ class BrowserContext:return session.cached_state- async def _update_state(self, focus_element: int = -1) -> BrowserState:+ async def _get_updated_state(self, focus_element: int = -1) -> BrowserState:"""Update and return state."""session = await self.get_session()diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.pyindex 98ca74354..7eb5cbe62 100644--- a/browser_use/browser/tests/test_clicks.py+++ b/browser_use/browser/tests/test_clicks.py@@ -48,7 +48,7 @@ async def test_highlight_elements():while True:try:# await asyncio.sleep(10)- state = await context.get_state()+ state = await context.get_state(True)with open('./tmp/page.json', 'w') as f:json.dump(diff --git a/browser_use/dom/clickable_element_processor/service.py b/browser_use/dom/clickable_element_processor/service.pynew file mode 100644index 000000000..dd2da869a--- /dev/null+++ b/browser_use/dom/clickable_element_processor/service.py@@ -0,0 +1,70 @@+import hashlib++from browser_use.dom.views import DOMElementNode+++class ClickableElementProcessor:+ @staticmethod+ def get_clickable_elements_hashes(dom_element: DOMElementNode) -> set[str]:+ """Get all clickable elements in the DOM tree"""+ clickable_elements = ClickableElementProcessor.get_clickable_elements(dom_element)+ return {ClickableElementProcessor.hash_dom_element(element) for element in clickable_elements}++ @staticmethod+ def get_clickable_elements(dom_element: DOMElementNode) -> list[DOMElementNode]:+ """Get all clickable elements in the DOM tree"""+ clickable_elements = list()+ for child in dom_element.children:+ if isinstance(child, DOMElementNode):+ if child.highlight_index:+ clickable_elements.append(child)++ clickable_elements.extend(ClickableElementProcessor.get_clickable_elements(child))++ return list(clickable_elements)++ @staticmethod+ def hash_dom_element(dom_element: DOMElementNode) -> str:+ parent_branch_path = ClickableElementProcessor._get_parent_branch_path(dom_element)+ branch_path_hash = ClickableElementProcessor._parent_branch_path_hash(parent_branch_path)+ attributes_hash = ClickableElementProcessor._attributes_hash(dom_element.attributes)+ xpath_hash = ClickableElementProcessor._xpath_hash(dom_element.xpath)+ # text_hash = DomTreeProcessor._text_hash(dom_element)++ return ClickableElementProcessor._hash_string(f'{branch_path_hash}-{attributes_hash}-{xpath_hash}')++ @staticmethod+ def _get_parent_branch_path(dom_element: DOMElementNode) -> list[str]:+ parents: list[DOMElementNode] = []+ current_element: DOMElementNode = dom_element+ while current_element.parent is not None:+ parents.append(current_element)+ current_element = current_element.parent++ parents.reverse()++ return [parent.tag_name for parent in parents]++ @staticmethod+ def _parent_branch_path_hash(parent_branch_path: list[str]) -> str:+ parent_branch_path_string = '/'.join(parent_branch_path)+ return hashlib.sha256(parent_branch_path_string.encode()).hexdigest()++ @staticmethod+ def _attributes_hash(attributes: dict[str, str]) -> str:+ attributes_string = ''.join(f'{key}={value}' for key, value in attributes.items())+ return ClickableElementProcessor._hash_string(attributes_string)++ @staticmethod+ def _xpath_hash(xpath: str) -> str:+ return ClickableElementProcessor._hash_string(xpath)++ @staticmethod+ def _text_hash(dom_element: DOMElementNode) -> str:+ """ """+ text_string = dom_element.get_all_text_till_next_clickable_element()+ return ClickableElementProcessor._hash_string(text_string)++ @staticmethod+ def _hash_string(string: str) -> str:+ return hashlib.sha256(string.encode()).hexdigest()diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.pyindex 135f18404..8e2b2d49c 100644--- a/browser_use/dom/tests/extraction_test.py+++ b/browser_use/dom/tests/extraction_test.py@@ -8,7 +8,6 @@ from browser_use.agent.prompts import AgentMessagePromptfrom browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.browser.context import BrowserContext, BrowserContextConfigfrom browser_use.dom.service import DomService-from browser_use.utils import time_execution_syncdef count_string_tokens(string: str, model: str) -> tuple[int, float]:@@ -31,78 +30,6 @@ def count_string_tokens(string: str, model: str) -> tuple[int, float]:return token_count, price-async def test_process_html_file():- config = BrowserContextConfig(- cookies_file='cookies3.json',- disable_security=True,- wait_for_network_idle_page_load_time=1,- )-- browser = Browser(- config=BrowserConfig(- # chrome_instance_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- )- )- context = BrowserContext(browser=browser, config=config) # noqa: F821-- websites = [- 'https://kayak.com/flights',- 'https://immobilienscout24.de',- 'https://google.com',- 'https://amazon.com',- 'https://github.com',- ]-- async with context as context:- page = await context.get_current_page()- dom_service = DomService(page)-- for website in websites:- print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')- await page.goto(website)- time.sleep(2) # Additional wait for dynamic content-- async def test_viewport(expansion: int, description: str):- print(f'\n{description}:')- dom_state = await time_execution_sync(f'get_clickable_elements ({description})')(- dom_service.get_clickable_elements- )(highlight_elements=True, viewport_expansion=expansion)-- elements = dom_state.element_tree- selector_map = dom_state.selector_map- element_count = len(selector_map.keys())- token_count = count_string_tokens(elements.clickable_elements_to_string(), model='gpt-4o')-- print(f'Number of elements: {element_count}')- print(f'Token count: {token_count}')- return element_count, token_count-- expansions = [0, 100, 200, 300, 400, 500, 600, 1000, -1, -200]- results = []-- for i, expansion in enumerate(expansions):- description = (- f'{i + 1}. Expansion {expansion}px' if expansion >= 0 else f'{i + 1}. All elements ({expansion} expansion)'- )- count, tokens = await test_viewport(expansion, description)- results.append((count, tokens))- input('Press Enter to continue...')- await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')-- # Print comparison summary- print('\nComparison Summary:')- for i, (count, tokens) in enumerate(results):- expansion = expansions[i]- description = f'Expansion {expansion}px' if expansion >= 0 else 'All elements (-1)'- initial_count, initial_tokens = results[0]- print(f'{description}: {count} elements (+{count - initial_count}), {tokens} tokens')-- input('\nPress Enter to continue to next website...')-- # Clear highlights before next website- await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')--TIMEOUT = 60DEFAULT_INCLUDE_ATTRIBUTES = [@@ -135,11 +62,11 @@ async def test_focus_vs_all_elements():context = BrowserContext(browser=browser, config=config) # noqa: F821websites = [- # 'https://kayak.com/flights',+ 'https://kayak.com/flights',# 'https://en.wikipedia.org/wiki/Humanist_Party_of_Ontario',# 'https://www.google.com/travel/flights?tfs=CBwQARoJagcIARIDTEpVGglyBwgBEgNMSlVAAUgBcAGCAQsI____________AZgBAQ&tfu=KgIIAw&hl=en-US&gl=US',# # 'https://www.concur.com/?&cookie_preferences=cpra',- 'https://immobilienscout24.de',+ # 'https://immobilienscout24.de','https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit','https://www.zeiss.com/career/en/job-search.html?page=1','https://www.mlb.com/yankees/stats/',@@ -168,7 +95,7 @@ async def test_focus_vs_all_elements():# Get/refresh the state (includes removing old highlights)print('\nGetting page state...')- all_elements_state = await context.get_state()+ all_elements_state = await context.get_state(True)selector_map = all_elements_state.selector_maptotal_elements = len(selector_map.keys())diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 17c9b9983..bac702de3 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -72,6 +72,13 @@ class DOMElementNode(DOMBaseNode):page_coordinates: Optional[CoordinateSet] = Noneviewport_info: Optional[ViewportInfo] = None+ """+ ### State injected by the browser context.++ The idea is that the clickable elements are sometimes persistent from the previous page -> tells the model which objects are new/_how_ the state has changed+ """+ is_new: Optional[bool] = None+def __json__(self) -> dict:return {'tag_name': self.tag_name,@@ -187,7 +194,13 @@ class DOMElementNode(DOMBaseNode):attributes_html_str = ' '.join(f"{key}='{value}'" for key, value in attributes_to_include.items())# Build the line- line = f'{depth_str}[{node.highlight_index}]<{node.tag_name}'+ if node.is_new:+ highlight_indicator = f'*[{node.highlight_index}]*'+ else:+ highlight_indicator = f'[{node.highlight_index}]'++ line = f'{depth_str}{highlight_indicator}<{node.tag_name}'+if attributes_html_str:line += f' {attributes_html_str}'