Skip to content

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

fix: enable downloads

j0yk1ll400c8b813ae3
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 90e57f1da..561504a7e 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -76,6 +76,9 @@ class BrowserContextConfig:
save_recording_path: None
Path to save video recordings
+ save_downloads_path: None
+ Path to save downloads to
+
trace_path: None
Path to save trace files. It will auto name the file with the TRACE_PATH/{context_id}.zip
@@ -108,6 +111,7 @@ class BrowserContextConfig:
no_viewport: Optional[bool] = None
save_recording_path: str | None = None
+ save_downloads_path: str | None = None
trace_path: str | None = None
locale: str | None = None
user_agent: str = (
@@ -926,7 +930,7 @@ class BrowserContext:
except Exception as e:
raise Exception(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
- async def _click_element_node(self, element_node: DOMElementNode):
+ async def _click_element_node(self, element_node: DOMElementNode) -> Optional[str]:
"""
Optimized method to click an element using xpath.
"""
@@ -942,21 +946,40 @@ class BrowserContext:
if element is None:
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.config.save_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:
+ await click_func()
+ download = await download_info.value
+ # If the download succeeds, save to disk
+ download_path = os.path.join(self.config.save_downloads_path, download.suggested_filename)
+ await download.save_as(download_path)
+ logger.debug(f'Download triggered. Saved file to: {download_path}')
+ return download_path
+ except TimeoutError:
+ # If no download is triggered, treat as normal click
+ logger.debug('No download triggered within timeout. Checking navigation...')
+ await page.wait_for_load_state()
+ await self._check_and_handle_navigation(page)
+ else:
+ # Standard click logic if no download is expected
+ await click_func()
+ await page.wait_for_load_state()
+ await self._check_and_handle_navigation(page)
+
# await element.scroll_into_view_if_needed()
try:
- await element.click(timeout=1500)
- await page.wait_for_load_state()
- # Check if navigation occurred and if the new URL is allowed
- await self._check_and_handle_navigation(page)
+ return await perform_click(lambda: element.click(timeout=1500))
except URLNotAllowedError as e:
raise e
except Exception:
try:
- await page.evaluate('(el) => el.click()', element)
- await page.wait_for_load_state()
- # Check if navigation occurred and if the new URL is allowed
- await self._check_and_handle_navigation(page)
+ return await perform_click(lambda: page.evaluate('(el) => el.click()', element))
except URLNotAllowedError as e:
raise e
except Exception as e:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 62a0adaec..c55d642ae 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -4,7 +4,6 @@ import logging
from typing import Optional, Type
from main_content_extractor import MainContentExtractor
-from playwright.async_api import Page
from pydantic import BaseModel
from browser_use.agent.views import ActionModel, ActionResult
@@ -103,8 +102,11 @@ class Controller:
msg = None
try:
- await browser._click_element_node(element_node)
- msg = f'🖱️ Clicked button with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
+ download_path = await browser._click_element_node(element_node)
+ if download_path:
+ msg = f'💾 Downloaded file to {download_path}'
+ else:
+ msg = f'🖱️ Clicked button with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
logger.info(msg)
logger.debug(f'Element xpath: {element_node.xpath}')
diff --git a/examples/features/download_file.py b/examples/features/download_file.py
new file mode 100644
index 000000000..5e2782cdd
--- /dev/null
+++ b/examples/features/download_file.py
@@ -0,0 +1,37 @@
+import asyncio
+import os
+
+from dotenv import load_dotenv
+from langchain_google_genai import ChatGoogleGenerativeAI
+from pydantic import SecretStr
+
+from browser_use import Agent
+from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser.context import BrowserContextConfig
+
+load_dotenv()
+api_key = os.getenv('GEMINI_API_KEY')
+if not api_key:
+ raise ValueError('GEMINI_API_KEY is not set')
+llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))
+browser = Browser(
+ config=BrowserConfig(
+ new_context_config=BrowserContextConfig(save_downloads_path=os.path.join(os.path.expanduser('~'), 'downloads'))
+ )
+)
+
+
+async def run_download():
+ agent = Agent(
+ task=('Go to "https://file-examples.com/" and download the smallest doc file.'),
+ llm=llm,
+ max_actions_per_step=8,
+ use_vision=True,
+ browser=browser,
+ )
+ await agent.run(max_steps=25)
+ await browser.close()
+
+
+if __name__ == '__main__':
+ asyncio.run(run_download())