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
Rerun works
magmueller519881a7b37d
diff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.pyindex a02e387af..d1de5c499 100644--- a/browser_use/agent/tests.py+++ b/browser_use/agent/tests.py@@ -29,6 +29,7 @@ def sample_browser_state():children=[],),selector_map={},+ interacted_element=None,)diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 704c7b981..fa8b0c8ab 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -71,13 +71,8 @@ class AgentHistory(BaseModel):model_output: AgentOutput, selector_map: SelectorMap) -> DOMHistoryElement | None:if model_output:- # check if action has index param- action_values = model_output.action.model_dump(exclude_unset=True).values()- params = next(iter(action_values))-- index_exists = 'index' in params- if index_exists:- index = params['index']+ index = model_output.action.get_index()+ if index:el: DOMElementNode = selector_map[index]return HistoryTreeProcessor.convert_dom_element_to_history_element(el)diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex be801c24e..cc8395d44 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -26,8 +26,9 @@ class BrowserState(DOMState):data = {}data['tabs'] = [tab.model_dump() for tab in self.tabs]data['screenshot'] = self.screenshot- data['element_tree'] = None- data['interacted_element'] = None+ data['interacted_element'] = (+ self.interacted_element.to_dict() if self.interacted_element else None+ )data['url'] = self.urldata['title'] = self.titlereturn datadiff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.pyindex b11f6375e..05e07edd1 100644--- a/browser_use/controller/registry/views.py+++ b/browser_use/controller/registry/views.py@@ -38,6 +38,28 @@ class ActionModel(BaseModel):#model_config = ConfigDict(arbitrary_types_allowed=True)+ def get_index(self) -> int | None:+ """Get the index of the action"""+ # {'clicked_element': {'index':5}}+ params = self.model_dump(exclude_unset=True).values()+ if not params:+ return None+ for param in params:+ if 'index' in param:+ return param['index']+ return None++ def set_index(self, index: int):+ """Overwrite the index of the action"""+ # Get the action name and params+ action_data = self.model_dump(exclude_unset=True)+ action_name = next(iter(action_data.keys()))+ action_params = getattr(self, action_name)++ # Update the index directly on the model+ if hasattr(action_params, 'index'):+ action_params.index = index+class ActionRegistry(BaseModel):"""Model representing the action registry"""diff --git a/browser_use/dom/history_tree_processor.py b/browser_use/dom/history_tree_processor.pyindex c01ccc238..ee591ccce 100644--- a/browser_use/dom/history_tree_processor.py+++ b/browser_use/dom/history_tree_processor.py@@ -25,7 +25,7 @@ class DOMHistoryElement:attributes: dict[str, str]shadow_root: bool = False- def model_dump(self) -> dict:+ def to_dict(self) -> dict:return {'tag_name': self.tag_name,'xpath': self.xpath,diff --git a/examples/flight_search.py b/examples/flight_search.pyindex 6018b7eb0..92ca63df8 100644--- a/examples/flight_search.py+++ b/examples/flight_search.py@@ -11,7 +11,8 @@ from doctest import OutputCheckerfrom pprint import pprintfrom browser_use.agent.views import AgentBrain-from browser_use.dom.views import SelectorMap+from browser_use.dom.history_tree_processor import HistoryTreeProcessor+from browser_use.dom.views import DOMElementNode, SelectorMapsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import asyncio@@ -21,8 +22,8 @@ from langchain_openai import ChatOpenAIfrom browser_use import ActionModel, Agent, AgentHistoryList, Controllerfrom browser_use.agent.views import AgentOutput-llm = ChatOpenAI(model='gpt-4o-mini')-controller = Controller(keep_open=False)+llm = ChatOpenAI(model='gpt-4o')+controller = Controller(keep_open=False, cookies_path='cookies.json')@controller.registry.action(description='Prints the secret text')@@ -31,28 +32,27 @@ async def secret_text(secret_text: str) -> None:agent = Agent(- # task='Find flights on kayak.com from Zurich to Beijing on 25.12.2024 to 02.02.2025',- task='Search for elon musk on google and click the first result scroll down',+ # task='Go to kayak.com and search for flights from Zurich to Beijing and then done.',+ task='Find flights on kayak.com from Zurich to Beijing on 25.12.2024 to 02.02.2025',+ # task='Search for elon musk on google and click the first result scroll down',llm=llm,controller=controller,)async def main():- history: AgentHistoryList = await agent.run(2)+ history: AgentHistoryList = await agent.run(5)# agent.save_history(file)await controller.browser.close(force=True)history.save_to_file('AgentHistoryList.json')- print(f'history: {history}')-await rerun_task()async def rerun_task():# create new controller and agent- controller2 = Controller(keep_open=False)+ controller2 = Controller(keep_open=False, cookies_path='cookies.json')agent2 = Agent(task='',llm=llm,@@ -70,44 +70,40 @@ async def rerun_task():print(actions)# close controller-+ # get all interacted elements+ interacted_elements = [h.state.interacted_element for h in history2.history]for i, history_item in enumerate(history2.history):- print(f'history_item {i}')+ print(f'{i} {actions[i]} ')ouput = history_item.model_outputif ouput and ouput.action:+ goal = ouput.current_state.next_goal+ print(f'goal: {goal}')try:# check if state is the same as previous- prev_selector_map: SelectorMap = history_item.state.selector_map+ old_el = history_item.state.interacted_elementstate = await controller2.browser.get_state()- current_selector_map: SelectorMap = state.selector_map- # check which values are different- diff = [- v1- for v1, v2 in zip(prev_selector_map.values(), current_selector_map.values())- if v1 != v2- ]- # keys unique difference- diff = prev_selector_map.keys() - current_selector_map.keys()- if diff:- print(f'diff: {diff}')- continue-- # get exclude unset=True field in action- action = ouput.action.model_dump(exclude_unset=True)- # get index of clicked if index param in output.action e.g. click_element(index=0), input(index=0, value='test'),- # check if index is in param of action {'click_element': {'index': 9, 'num_clicks': 1}}- params = dict(action.values())- index_exists = 'index' in params- if index_exists:- index = params['index']- # get element with index from prev selector map- prev_element = prev_selector_map[index]- # get element with index from current selector map- current_element = current_selector_map[index]- if prev_element != current_element:- print(f'element changed: {prev_element} -> {current_element}')+ tree = state.element_tree++ if old_el and tree:+ element: DOMElementNode | None = (+ HistoryTreeProcessor.find_history_element_in_tree(old_el, tree)+ )+ if element:+ index = element.highlight_index+ old_index = ouput.action.get_index()+ print(f'same element found with index: {index} and old index: {old_index}')++ if old_index != index and index is not None:+ ouput.action.set_index(index)+ else:+ print(f'old element not found in new tree')continue- action_model = await controller2.act(action)++ action_result = await controller2.act(ouput.action)+ if action_result.error:+ print(f'Step {i} failed: {action_result.error}')+ else:+ print(f'Step {i} succeeded: {action_result.extracted_content}')except Exception as e:print(f'Error executing action {ouput.action}: {e}')