Skip to content

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

File upload example

magmuellerafa2e4ffc984
diff --git a/examples/file_upload.py b/examples/file_upload.py
index 1e8d2fe0f..5af26863b 100644
--- a/examples/file_upload.py
+++ b/examples/file_upload.py
@@ -2,6 +2,8 @@ import os
import sys
from pathlib import Path
+from browser_use.agent.views import ActionResult
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import asyncio
@@ -11,23 +13,52 @@ from browser_use import Agent, Controller
from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.browser.context import BrowserContext
+CV = Path.cwd() / 'examples/test_cv.txt'
+import logging
+
+logger = logging.getLogger(__name__)
+
# Initialize controller first
-browser = Browser(config=BrowserConfig(headless=False))
+browser = Browser(
+ config=BrowserConfig(
+ headless=False,
+ chrome_instance_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ )
+)
controller = Controller()
@controller.action(
- 'Upload file - the file name is inside the function - you only need to call this with the correct index',
+ 'Upload file to element ',
requires_browser=True,
)
async def upload_file(index: int, browser: BrowserContext):
- element = await browser.get_element_by_index(index)
- my_file = Path.cwd() / 'examples/test_cv.txt'
- if not element:
- raise Exception(f'Element with index {index} not found')
+ path = str(CV.absolute())
+ dom_el = await browser.get_dom_element_by_index(index)
+
+ if dom_el is None:
+ return ActionResult(error=f'No element found at index {index}')
+
+ file_upload_dom_el = dom_el.get_file_upload_element()
- await element.set_input_files(str(my_file.absolute()))
- return f'Uploaded file to index {index}'
+ if file_upload_dom_el is None:
+ logger.info(f'No file upload element found at index {index}')
+ return ActionResult(error=f'No file upload element found at index {index}')
+
+ file_upload_el = await browser.get_locate_element(file_upload_dom_el)
+
+ if file_upload_el is None:
+ logger.info(f'No file upload element found at index {index}')
+ return ActionResult(error=f'No file upload element found at index {index}')
+
+ try:
+ await file_upload_el.set_input_files(path)
+ msg = f'Successfully uploaded file to index {index}'
+ logger.info(msg)
+ return ActionResult(extracted_content=msg)
+ except Exception as e:
+ logger.debug(f'Error in set_input_files: {str(e)}')
+ return ActionResult(error=f'Failed to upload file to index {index}')
@controller.action('Close file dialog', requires_browser=True)
@@ -37,10 +68,10 @@ async def close_file_dialog(browser: BrowserContext):
async def main():
- sites = [
- 'https://kzmpmkh2zfk1ojnpxfn1.lite.vusercontent.net/',
- ]
- task = f'go to {" ".join(sites)} each in new tabs and Upload my file then subbmit and stop'
+ task = (
+ f'go to https://kzmpmkh2zfk1ojnpxfn1.lite.vusercontent.net/'
+ f' and upload to each upload field my file'
+ )
model = ChatOpenAI(model='gpt-4o')
agent = Agent(
@@ -52,12 +83,6 @@ async def main():
await agent.run()
- history_file_path = 'AgentHistoryList.json'
- agent.save_history(file_path=history_file_path)
-
- agent2 = Agent(llm=model, controller=controller, task='', browser=browser)
- await agent2.load_and_rerun(history_file_path)
-
await browser.close()
input('Press Enter to close...')