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
much better extraction test
Gregor Žuničef55e2ea13d3
diff --git a/.python-version b/.python-versionindex 2c0733315..fdcfcfdfc 100644--- a/.python-version+++ b/.python-version@@ -1 +1 @@-3.11+3.12\ No newline at end of filediff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex a970bbf6a..076762f19 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -64,12 +64,12 @@ class AgentMessagePrompt:self,state: 'BrowserState',result: Optional[List['ActionResult']] = None,- include_attributes: list[str] = [],+ include_attributes: list[str] | None = None,step_info: Optional['AgentStepInfo'] = None,):self.state = stateself.result = result- self.include_attributes = include_attributes+ self.include_attributes = include_attributes or []self.step_info = step_infodef get_user_message(self, use_vision: bool = True) -> HumanMessage:diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.pyindex 4aeb3c671..980ff1e16 100644--- a/browser_use/dom/tests/extraction_test.py+++ b/browser_use/dom/tests/extraction_test.py@@ -1,8 +1,11 @@import asyncio+import json+import osimport timefrom langchain_openai import ChatOpenAI+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@@ -89,6 +92,19 @@ async def test_process_html_file():TIMEOUT = 60+DEFAULT_INCLUDE_ATTRIBUTES = [+ 'title',+ 'type',+ 'name',+ 'role',+ 'aria-label',+ 'placeholder',+ 'value',+ 'alt',+ 'aria-expanded',+ 'data-date-format',+]+async def test_focus_vs_all_elements():config = BrowserContextConfig(@@ -144,7 +160,25 @@ async def test_focus_vs_all_elements():total_elements = len(selector_map.keys())print(f'Total number of elements: {total_elements}')- print(all_elements_state.element_tree.clickable_elements_to_string())+ # print(all_elements_state.element_tree.clickable_elements_to_string())+ prompt = AgentMessagePrompt(+ state=all_elements_state,+ result=None,+ include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,+ step_info=None,+ )+ # print(prompt.get_user_message(use_vision=False).content)+ # Write the user message to a file for analysis+ user_message = prompt.get_user_message(use_vision=False).content+ os.makedirs('./tmp', exist_ok=True)+ with open('./tmp/user_message.txt', 'w', encoding='utf-8') as f:+ f.write(user_message)+ print('User message written to ./tmp/user_message.txt')++ # also save all_elements_state.element_tree.clickable_elements_to_string() to a file+ with open('./tmp/clickable_elements.json', 'w', encoding='utf-8') as f:+ f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))+ print('Clickable elements written to ./tmp/clickable_elements.json')answer = input("Enter element index to click, text to input (after click), or 'q' to quit: ")diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex f0acd9f86..e8460ed7f 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -16,6 +16,9 @@ class DOMBaseNode:# Use None as default and set parent later to avoid circular reference issuesparent: Optional['DOMElementNode']+ def __json__(self) -> dict:+ raise NotImplementedError('DOMBaseNode is an abstract class')+@dataclass(frozen=False)class DOMTextNode(DOMBaseNode):@@ -42,6 +45,12 @@ class DOMTextNode(DOMBaseNode):return Falsereturn self.parent.is_top_element+ def __json__(self) -> dict:+ return {+ 'text': self.text,+ 'type': self.type,+ }+@dataclass(frozen=False)class DOMElementNode(DOMBaseNode):@@ -63,6 +72,22 @@ class DOMElementNode(DOMBaseNode):page_coordinates: Optional[CoordinateSet] = Noneviewport_info: Optional[ViewportInfo] = None+ def __json__(self) -> dict:+ return {+ 'tag_name': self.tag_name,+ 'xpath': self.xpath,+ 'attributes': self.attributes,+ 'is_visible': self.is_visible,+ 'is_interactive': self.is_interactive,+ 'is_top_element': self.is_top_element,+ 'is_in_viewport': self.is_in_viewport,+ 'shadow_root': self.shadow_root,+ 'highlight_index': self.highlight_index,+ 'viewport_coordinates': self.viewport_coordinates,+ 'page_coordinates': self.page_coordinates,+ 'children': [child.__json__() for child in self.children],+ }+def __repr__(self) -> str:tag_str = f'<{self.tag_name}'diff --git a/examples/simple.py b/examples/simple.pyindex c755e49fb..d2071420b 100644--- a/examples/simple.py+++ b/examples/simple.py@@ -17,7 +17,7 @@ llm = ChatOpenAI(model='gpt-4o',temperature=0.0,)-task = 'Find the founders of browser-use and draft them a short personalized message'+task = 'Go to kayak.com and find the cheapest flight from Zurich to San Francisco on 2025-05-01'agent = Agent(task=task, llm=llm)