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
Merge remote-tracking branch 'origin/gregpr07/bu-85-make-iframes-and-shadow-elements-work-with-dom-service' into feature/reexecutable-script
magmueller6669a436c77f
diff --cc browser_use/agent/service.pyindex c32379e67,66a726c85..4afe62d24--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -8,16 -8,10 +8,12 @@@ import uuifrom typing import Any, Optional, Type, TypeVarfrom dotenv import load_dotenv- from langchain_anthropic import ChatAnthropicfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import (- AIMessage,BaseMessage,+ HumanMessage,+ SystemMessage,)- from langchain_openai import ChatOpenAIfrom openai import RateLimitErrorfrom pydantic import BaseModel, ValidationErrordiff --cc browser_use/browser/service.pyindex 6875a886b,184135aa2..8f5e87bd6--- a/browser_use/browser/service.py+++ b/browser_use/browser/service.py@@@ -4,15 -4,19 +4,22 @@@ Playwright browser on steroidsimport asyncioimport base64+import jsonimport logging+import osimport timefrom dataclasses import dataclass+from pathlib import Pathfrom playwright.async_api import Browser as PlaywrightBrowser- from playwright.async_api import BrowserContext, ElementHandle, Page, Playwright, async_playwright+ from playwright.async_api import (+ BrowserContext,+ ElementHandle,+ FrameLocator,+ Page,+ Playwright,+ async_playwright,+ )from browser_use.browser.views import BrowserError, BrowserState, TabInfofrom browser_use.dom.service import DomService@@@ -38,12 -42,12 +45,16 @@@ class BrowserMAXIMUM_WAIT_TIME = 5def __init__(- self, headless: bool = False, keep_open: bool = False, cookies_path: str | None = None- self, headless: bool = False, keep_open: bool = False, disable_security: bool = False++ self,++ headless: bool = False,++ keep_open: bool = False,++ cookies_path: str | None = None,++ disable_security: bool = False,):self.headless = headlessself.keep_open = keep_open+ self.cookies_file = cookies_path-+ self.disable_security = disable_security-# Initialize these as None - they'll be set up when neededself.session: BrowserSession | None = None@@@ -123,15 -148,10 +155,17 @@@'(KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'),java_script_enabled=True,+ bypass_csp=self.disable_security,+ ignore_https_errors=self.disable_security,)+ # Load cookies if they exist+ if self.cookies_file and os.path.exists(self.cookies_file):+ with open(self.cookies_file, 'r') as f:+ cookies = json.load(f)+ logger.info(f'Loaded {len(cookies)} cookies from {self.cookies_file}')+ await context.add_cookies(cookies)+# Expose anti-detection scriptsawait context.add_init_script("""@@@ -484,26 -513,8 +536,20 @@@session = await self.get_session()return session.cached_state.selector_map- async def get_xpath(self, index: int) -> str:- selector_map = await self.get_selector_map()- return selector_map[index]-async def get_element_by_index(self, index: int) -> ElementHandle | None:- page = await self.get_current_page()- return await page.wait_for_selector(- await self.get_xpath(index), timeout=2500, state='visible'- )+ selector_map = await self.get_selector_map()+ return await self.get_locate_element(selector_map[index])- # endregion+ async def save_cookies(self):+ """Save current cookies to file"""+ if self.session and self.session.context and self.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.cookies_file):+ os.makedirs(os.path.dirname(self.cookies_file), exist_ok=True)+ with open(self.cookies_file, 'w') as f:+ json.dump(cookies, f)+ except Exception as e:+ logger.error(f'Failed to save cookies: {str(e)}')diff --cc browser_use/controller/service.pyindex ed84448c2,afd1b6d58..222ae0eec--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@@ -23,9 -23,11 +23,18 @@@ logger = logging.getLogger(__name__class Controller:def __init__(- self, headless: bool = False, keep_open: bool = False, cookies_path: str | None = None- self, headless: bool = False, keep_open: bool = False, disable_security: bool = False++ self,++ headless: bool = False,++ keep_open: bool = False,++ cookies_path: str | None = None,++ disable_security: bool = False,):- self.browser = Browser(headless=headless, keep_open=keep_open, cookies_path=cookies_path)+ self.browser = Browser(- headless=headless, keep_open=keep_open, disable_security=disable_security++ headless=headless,++ keep_open=keep_open,++ cookies_path=cookies_path,++ disable_security=disable_security,+ )self.registry = Registry()self._register_default_actions()