Skip to content

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

Merge remote-tracking branch 'origin/main' into feature/reexecutable-script

magmuellerc39bf65da189
diff --cc browser_use/__init__.py
index f31fbf46c,ed7f441b5..0e2a4d3f3
--- a/browser_use/__init__.py
+++ b/browser_use/__init__.py
@@@ -4,10 -4,9 +4,11 @@@ setup_logging(
from browser_use.agent.prompts import SystemPrompt as SystemPrompt
from browser_use.agent.service import Agent as Agent
+from browser_use.agent.views import ActionModel as ActionModel
from browser_use.agent.views import ActionResult as ActionResult
+from browser_use.agent.views import AgentHistoryList as AgentHistoryList
from browser_use.browser.service import Browser as Browser
+ from browser_use.browser.service import BrowserConfig as BrowserConfig
from browser_use.controller.service import Controller as Controller
from browser_use.dom.service import DomService as DomService
diff --cc browser_use/browser/service.py
index beada470e,20d1ab76a..ebc6950e5
--- a/browser_use/browser/service.py
+++ b/browser_use/browser/service.py
@@@ -161,10 -202,9 +203,10 @@@ class Browser
)
# Load cookies if they exist
- if self.cookies_file and os.path.exists(self.cookies_file):
- with open(self.cookies_file, 'r') as f:
+ if self.config.cookies_file and os.path.exists(self.config.cookies_file):
+ with open(self.config.cookies_file, 'r') as f:
cookies = json.load(f)
- logger.info(f'Loaded {len(cookies)} cookies from {self.cookies_file}')
++ logger.info(f'Loaded {len(cookies)} cookies from {self.config.cookies_file}')
await context.add_cookies(cookies)
# Expose anti-detection scripts
@@@ -236,9 -437,10 +439,9 @@@
if self.session is None:
return
- if self.config.cookies_file:
- await self.save_cookies()
+ await self.save_cookies()
- if force and not self.keep_open:
+ if force and not self.config.keep_open:
session = await self.get_session()
await session.browser.close()
await session.playwright.stop()
@@@ -543,17 -808,13 +810,17 @@@
async def save_cookies(self):
"""Save current cookies to file"""
- if self.session and self.session.context and self.cookies_file:
+ if self.session and self.session.context and self.config.cookies_file:
try:
cookies = await self.session.context.cookies()
- logger.info(f'Saving {len(cookies)} cookies to {self.cookies_file}')
- # maybe file is just a file name then i get
- if os.path.dirname(self.config.cookies_file):
- os.makedirs(os.path.dirname(self.config.cookies_file), exist_ok=True)
++ logger.info(f'Saving {len(cookies)} cookies to {self.config.cookies_file}')
+
+ # Check if the path is a directory and create it if necessary
- dirname = os.path.dirname(self.cookies_file)
++ dirname = os.path.dirname(self.config.cookies_file)
+ if dirname:
+ os.makedirs(dirname, exist_ok=True)
+
- with open(self.cookies_file, 'w') as f:
+ with open(self.config.cookies_file, 'w') as f:
json.dump(cookies, f)
except Exception as e:
- logger.error(f'Failed to save cookies: {str(e)}')
+ logger.warning(f'Failed to save cookies: {str(e)}')
diff --cc browser_use/browser/tests/test_clicks.py
index b0258aa2a,8b9c97aef..ad9e94c75
--- a/browser_use/browser/tests/test_clicks.py
+++ b/browser_use/browser/tests/test_clicks.py
@@@ -8,10 -8,9 +8,10 @@@ from browser_use.dom.views import Eleme
from browser_use.utils import time_execution_sync
+# run with: pytest browser_use/browser/tests/test_clicks.py
@pytest.mark.asyncio
async def test_highlight_elements():
- browser = Browser(headless=False, keep_open=False, disable_security=True)
+ browser = Browser(config=BrowserConfig(headless=False, keep_open=False, disable_security=True))
session = await browser.get_session()
@@@ -42,13 -38,8 +42,10 @@@
# browser.highlight_selector_map_elements
# )(state.selector_map)
- # print(state.dom_items_to_string(use_tabs=False))
- # print(state.selector_map)
-
# Find and print duplicate XPaths
xpath_counts = {}
+ if not state.selector_map:
+ continue
for selector in state.selector_map.values():
xpath = selector.xpath
if xpath in xpath_counts:
@@@ -62,9 -53,8 +59,9 @@@
print(f'XPath: {xpath}')
print(f'Count: {count}\n')
- print(state.selector_map.keys(), 'Selector map keys')
- print(state.element_tree.clickable_elements_to_string())
+ print(list(state.selector_map.keys()), 'Selector map keys')
+ if state.element_tree:
- print(state.element_tree.clickable_elements_to_string(use_tabs=False))
++ print(state.element_tree.clickable_elements_to_string())
action = input('Select next action: ')
await time_execution_sync('remove_highlight_elements')(browser.remove_highlights)()
diff --cc browser_use/controller/service.py
index c40f51b94,755b56b7f..3223bb47d
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@@ -70,7 -62,8 +62,7 @@@ class Controller
session = await browser.get_session()
state = session.cached_state
-- if params.index not in state.selector_map:
- print(state.selector_map)
++ if state.selector_map is None or params.index not in state.selector_map:
raise Exception(
f'Element with index {params.index} does not exist - retry or use alternative actions'
)
@@@ -100,7 -93,7 +92,7 @@@
session = await browser.get_session()
state = session.cached_state
-- if params.index not in state.selector_map:
++ if state.selector_map is None or params.index not in state.selector_map:
raise Exception(
f'Element index {params.index} does not exist - retry or use alternative actions'
)
diff --cc browser_use/dom/views.py
index 8936c0001,e5e0607bb..9e43e83f0
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@@ -145,6 -141,5 +143,6 @@@ from browser_use.dom.history_tree_proce
@dataclass
class DOMState:
- element_tree: DOMElementNode
- selector_map: SelectorMap
+ element_tree: DOMElementNode | None
- interacted_element: DOMHistoryElement | None
+ selector_map: SelectorMap | None
++ interacted_element: DOMHistoryElement | None
diff --cc examples/flight_search.py
index e68f94361,ffc1c94f8..0275e521b
--- a/examples/flight_search.py
+++ b/examples/flight_search.py
@@@ -19,18 -13,9 +19,18 @@@ import asynci
from langchain_openai import ChatOpenAI
-from browser_use import Agent
+from browser_use import ActionModel, Agent, AgentHistoryList, Controller
+from browser_use.agent.views import AgentOutput
llm = ChatOpenAI(model='gpt-4o')
- controller = Controller(keep_open=False, cookies_path='cookies.json')
++controller = Controller()
+
+
[email protected](description='Prints the secret text')
+async def secret_text(secret_text: str) -> None:
+ print(secret_text)
+
+
agent = Agent(
task='Find flights on kayak.com from Zurich to Beijing on 25.12.2024 to 02.02.2025',
llm=llm,