Skip to content

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

rename downloads_dir to downloads_path

Nick Sweeting767a75e2bf10
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index 19328d0c7..1e053b4d9 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -437,7 +437,11 @@ class BrowserLaunchArgs(BaseModel):
slow_mo: float = Field(default=0, description='Slow down actions by this many milliseconds.')
timeout: float = Field(default=30000, description='Default timeout in milliseconds for connecting to a remote browser.')
proxy: ProxySettings | None = Field(default=None, description='Proxy settings to use to connect to the browser.')
- downloads_path: str | Path | None = Field(default=None, description='Directory to save downloads to.')
+ downloads_path: str | Path | None = Field(
+ default=None,
+ description='Directory to save downloads to.',
+ validation_alias=AliasChoices('downloads_dir', 'save_downloads_path'),
+ )
traces_dir: str | Path | None = Field(default=None, description='Directory to save HAR trace files to.')
handle_sighup: bool = Field(
default=True, description='Whether playwright should swallow SIGHUP signals and kill the browser.'
@@ -601,14 +605,6 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
# description='Directory containing .crx extension files.',
# )
- # # --- File paths ---
- downloads_dir: Path | str | None = Field(
- default=Path('~/.config/browseruse/downloads').expanduser(),
- description='Directory for downloads.',
- validation_alias=AliasChoices('save_downloads_path'),
- )
- # uploads_dir: Path | None = Field(default=None, description='Directory for uploads (defaults to downloads_dir if not set).')
-
def __repr__(self) -> str:
short_dir = str(self.user_data_dir).replace(str(Path('~').expanduser()), '~')
return f'BrowserProfile(user_data_dir={short_dir}, headless={self.headless})'
@@ -707,9 +703,9 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
f'⚠️ Multiple chrome processes may be trying to share user_data_dir={self.user_data_dir} which can lead to crashes and profile data corruption!'
)
- if self.downloads_dir:
- self.downloads_dir = Path(self.downloads_dir).expanduser().resolve()
- self.downloads_dir.mkdir(parents=True, exist_ok=True)
+ if self.downloads_path:
+ self.downloads_path = Path(self.downloads_path).expanduser().resolve()
+ self.downloads_path.mkdir(parents=True, exist_ok=True)
# def preinstall_extensions(self) -> None:
# """Preinstall the extensions."""
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index cdd708918..cbaf095eb 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -485,11 +485,10 @@ class BrowserSession(BaseModel):
# search for potentially conflicting local processes running on the same user_data_dir
for proc in psutil.process_iter(['pid', 'cmdline']):
if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
- logger.warning(
+ logger.error(
f'🚨 Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
f'already running with the same user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir)}'
)
- # self._fork_locked_user_data_dir()
break
# if a user_data_dir is provided, launch a persistent context with that user_data_dir
@@ -1001,9 +1000,12 @@ class BrowserSession(BaseModel):
raise Exception(f'Element: {repr(element_node)} not found')
async def perform_click(click_func):
- """Performs the actual click, handling both download
- and navigation scenarios."""
- if self.browser_profile.downloads_dir:
+ """Performs the actual click, handling both download and navigation scenarios."""
+
+ # only wait the 5s extra for potential downloads if they are enabled
+ # TODO: instead of blocking for 5s, we should register a non-block page.on('download') event
+ # and then check if the download has been triggered within the event handler
+ if self.browser_profile.downloads_path:
try:
# Try short-timeout expect_download to detect a file download has been been triggered
async with page.expect_download(timeout=5000) as download_info:
@@ -1011,8 +1013,8 @@ class BrowserSession(BaseModel):
download = await download_info.value
# Determine file path
suggested_filename = download.suggested_filename
- unique_filename = await self._get_unique_filename(self.browser_profile.downloads_dir, suggested_filename)
- download_path = os.path.join(self.browser_profile.downloads_dir, unique_filename)
+ unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, suggested_filename)
+ download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
await download.save_as(download_path)
logger.debug(f'⬇️ Download triggered. Saved file to: {download_path}')
return download_path
@@ -1022,7 +1024,7 @@ class BrowserSession(BaseModel):
await page.wait_for_load_state()
await self._check_and_handle_navigation(page)
else:
- # Standard click logic if no download is expected
+ # If downloads are disabled, just perform the click
await click_func()
await page.wait_for_load_state()
await self._check_and_handle_navigation(page)
@@ -1201,11 +1203,10 @@ class BrowserSession(BaseModel):
cookies_path = Path(self.browser_profile.cookies_file)
if not cookies_path.is_absolute():
- cookies_path = Path(self.browser_profile.downloads_dir or '.') / cookies_path
+ cookies_path = Path(self.browser_profile.downloads_path or '.') / cookies_path
try:
- cookies_data_text = await anyio.Path(cookies_path).read_text()
- cookies_data = json.loads(cookies_data_text)
+ cookies_data = json.loads(cookies_path.read_text())
if cookies_data:
await self.browser_context.add_cookies(cookies_data)
logger.info(f'🍪 Loaded {len(cookies_data)} cookies from cookies_file={_log_pretty_path(cookies_path)}')
@@ -1257,9 +1258,9 @@ class BrowserSession(BaseModel):
# @property
# def saved_downloads(self) -> list[Path]:
# """
- # Return a list of files in the downloads_dir.
+ # Return a list of files in the downloads_path.
# """
- # return list(Path(self.browser_profile.downloads_dir).glob('*'))
+ # return list(Path(self.browser_profile.downloads_path).glob('*'))
async def _wait_for_stable_network(self):
pending_requests = set()
diff --git a/examples/features/download_file.py b/examples/features/download_file.py
index 6a68d2477..912c55486 100644
--- a/examples/features/download_file.py
+++ b/examples/features/download_file.py
@@ -12,30 +12,29 @@ from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import SecretStr
from browser_use import Agent
-from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser import BrowserSession
api_key = os.getenv('GOOGLE_API_KEY')
if not api_key:
raise ValueError('GOOGLE_API_KEY is not set')
+
llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))
+
browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- downloads_dir='~/Downloads',
- user_data_dir='~/.config/browseruse/profiles/default',
- )
+ downloads_path='~/Downloads',
+ user_data_dir='~/.config/browseruse/profiles/default',
)
async def run_download():
agent = Agent(
- task=('Go to "https://file-examples.com/" and download the smallest doc file.'),
+ task='Go to "https://file-examples.com/" and download the smallest doc file.',
llm=llm,
max_actions_per_step=8,
use_vision=True,
browser_session=browser_session,
)
await agent.run(max_steps=25)
- await browser_session.close()
if __name__ == '__main__':
diff --git a/tests/ci/test_browser_session_cookies.py b/tests/ci/test_browser_session_cookies.py
index 53390f019..91410e1bc 100644
--- a/tests/ci/test_browser_session_cookies.py
+++ b/tests/ci/test_browser_session_cookies.py
@@ -195,11 +195,11 @@ class TestBrowserSessionCookies:
headless=True,
user_data_dir=None,
cookies_file='test_cookies.json', # Relative path
- downloads_dir=browser_profile_with_cookies.downloads_dir,
+ downloads_path=browser_profile_with_cookies.downloads_path,
)
# Copy test cookies to expected location
- expected_path = Path(profile.downloads_dir) / 'test_cookies.json'
+ expected_path = Path(profile.downloads_path) / 'test_cookies.json'
expected_path.parent.mkdir(parents=True, exist_ok=True)
expected_path.write_text(
json.dumps([{'name': 'relative_cookie', 'value': 'relative_value', 'domain': 'localhost', 'path': '/'}])