Skip to content

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

Merge branch 'main' into gregpr07/bu-85-make-iframes-and-shadow-elements-work-with-dom-service

Gregor Žunič40e8c05c7d68
diff --cc browser_use/agent/service.py
index 66a726c85,c32379e67..ef60b3fd7
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -8,10 -8,16 +8,12 @@@ import uui
from typing import Any, Optional, Type, TypeVar
from dotenv import load_dotenv
-from langchain_anthropic import ChatAnthropic
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import (
- AIMessage,
BaseMessage,
+ HumanMessage,
+ SystemMessage,
)
-from langchain_openai import ChatOpenAI
from openai import RateLimitError
from pydantic import BaseModel, ValidationError
diff --cc browser_use/browser/service.py
index 184135aa2,21e175f85..514dc636d
--- a/browser_use/browser/service.py
+++ b/browser_use/browser/service.py
@@@ -4,19 -4,15 +4,22 @@@ Playwright browser on steroids
import asyncio
import base64
+ import json
import logging
+ import os
import time
from dataclasses import dataclass
+ from pathlib import Path
from 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, TabInfo
from browser_use.dom.service import DomService
@@@ -42,11 -38,11 +45,12 @@@ class Browser
MAXIMUM_WAIT_TIME = 5
def __init__(
- 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
++ self, headless: bool = False, keep_open: bool = False, disable_security: bool = False, cookies_path: str | None = None
):
self.headless = headless
self.keep_open = keep_open
- self.cookies_file = cookies_path
+ self.disable_security = disable_security
++ self.cookies_file = cookies_path
# Initialize these as None - they'll be set up when needed
self.session: BrowserSession | None = None
@@@ -148,10 -123,14 +152,16 @@@
'(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)
+ await context.add_cookies(cookies)
+
# Expose anti-detection scripts
await context.add_init_script(
"""
@@@ -513,8 -483,25 +532,19 @@@
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()
+ # 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.py
index afd1b6d58,ed84448c2..f808b6dfb
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@@ -23,11 -23,9 +23,11 @@@ logger = logging.getLogger(__name__
class Controller:
def __init__(
- 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
++ self, headless: bool = False, keep_open: bool = False, disable_security: bool = False, cookies_path: str | None = None
):
- 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, disable_security=disable_security, cookies_path=cookies_path
+ )
self.registry = Registry()
self._register_default_actions()