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
Feature examples
Magnus Müller55b433d74036
diff --git a/examples/features/custom_user_agent.py b/examples/features/custom_user_agent.pydeleted file mode 100644index 9182efc29..000000000--- a/examples/features/custom_user_agent.py+++ /dev/null@@ -1,73 +0,0 @@-import argparse-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from browser_use import Agent-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.controller.service import Controller-from browser_use.llm import ChatAnthropic, ChatOpenAI---def get_llm(provider: str):- if provider == 'anthropic':- return ChatAnthropic(model='claude-3-5-sonnet-20240620', temperature=0.0)- elif provider == 'openai':- return ChatOpenAI(model='gpt-4.1', temperature=0.0)-- else:- raise ValueError(f'Unsupported provider: {provider}')---# NOTE: This example is to find your current user agent string to use it in the browser_context-task = 'go to https://whatismyuseragent.com and find the current user agent string '---controller = Controller()---parser = argparse.ArgumentParser()-parser.add_argument('--query', type=str, help='The query to process', default=task)-parser.add_argument(- '--provider',- type=str,- choices=['openai', 'anthropic'],- default='openai',- help='The model provider to use (default: openai)',-)--args = parser.parse_args()--llm = get_llm(args.provider)--browser_session = BrowserSession(- browser_profile=BrowserProfile(- user_agent='foobarfoo',- user_data_dir='~/.config/browseruse/profiles/default',- )-)--agent = Agent(- task=args.query,- llm=llm,- controller=controller,- browser_session=browser_session,- use_vision=True,- max_actions_per_step=1,-)---async def main():- await agent.run(max_steps=25)-- input('Press Enter to close the browser...')- await browser_session.kill()---asyncio.run(main())diff --git a/examples/features/download_file.py b/examples/features/download_file.pyindex 49ddfdc1c..2ac115135 100644--- a/examples/features/download_file.py+++ b/examples/features/download_file.py@@ -9,33 +9,22 @@ from dotenv import load_dotenvload_dotenv()-from browser_use import Agent-from browser_use.browser import BrowserSession-from browser_use.llm import ChatGoogle+from browser_use import Agent, BrowserProfile, BrowserSession, ChatGoogleapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')-assert api_key is not None, 'GOOGLE_API_KEY must be set'-llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)+llm = ChatGoogle(model='gemini-2.5-flash', api_key=api_key)-from browser_use.browser import BrowserProfile-browser_session = BrowserSession(- browser_profile=BrowserProfile(- downloads_path='~/Downloads',- user_data_dir='~/.config/browseruse/profiles/default',- )-)+browser_session = BrowserSession(browser_profile=BrowserProfile(downloads_path='~/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_session=browser_session,)await agent.run(max_steps=25)diff --git a/examples/features/drag_drop.py b/examples/features/drag_drop.pydeleted file mode 100644index c5f920cdb..000000000--- a/examples/features/drag_drop.py+++ /dev/null@@ -1,51 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()---from browser_use import Agent-from browser_use.llm import ChatGoogle--api_key = os.getenv('GOOGLE_API_KEY')-if not api_key:- raise ValueError('GOOGLE_API_KEY is not set')--# API key is automatically set from the environment variable GOOGLE_API_KEY-llm = ChatGoogle(model='gemini-2.0-flash-exp')---task_1 = """-Navigate to: https://sortablejs.github.io/Sortable/.-Then scroll down to the first examplw with title "Simple list example".-Drag the element with name "item 1" to below the element with name "item 3".-"""---task_2 = """-Navigate to: https://excalidraw.com/.-Click on the pencil icon (with index 40).-Then draw a triangle in the canvas.-Draw the triangle starting from coordinate (400,400).-You can use the drag and drop action to draw the triangle.-"""---async def run_search():- agent = Agent(- task=task_1,- llm=llm,- max_actions_per_step=1,- use_vision=True,- )-- await agent.run(max_steps=25)---if __name__ == '__main__':- asyncio.run(run_search())diff --git a/examples/features/initial_actions.py b/examples/features/initial_actions.pyindex 6ba530aa1..7e8d585c8 100644--- a/examples/features/initial_actions.py+++ b/examples/features/initial_actions.py@@ -15,7 +15,6 @@ llm = ChatOpenAI(model='gpt-4.1-mini')initial_actions = [{'go_to_url': {'url': 'https://www.google.com', 'new_tab': True}},{'go_to_url': {'url': 'https://en.wikipedia.org/wiki/Randomness', 'new_tab': True}},- {'scroll_down': {'amount': 1000}},]agent = Agent(task='What theories are displayed on the page?',diff --git a/examples/features/multi-tab_handling.py b/examples/features/multi_tab.pysimilarity index 83%rename from examples/features/multi-tab_handling.pyrename to examples/features/multi_tab.pyindex 7c8a8bb31..0f80f94f9 100644--- a/examples/features/multi-tab_handling.py+++ b/examples/features/multi_tab.py@@ -19,7 +19,7 @@ from browser_use import Agent, ChatOpenAI# video: https://preview.screen.studio/share/clenCmS6llm = ChatOpenAI(model='gpt-4.1-mini')agent = Agent(- task='open 3 tabs with elon musk, trump, and steve jobs, then go back to the first and stop',+ task='open 3 tabs with elon musk, sam altman, and steve jobs, then go back to the first and stop',llm=llm,)diff --git a/examples/features/multiple_tasks.py b/examples/features/multiple_tasks.pydeleted file mode 100644index 0da02d666..000000000--- a/examples/features/multiple_tasks.py+++ /dev/null@@ -1,84 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()---from browser_use import Agent-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.browser.profile import ViewportSize-from browser_use.llm import ChatGoogle--api_key = os.getenv('GOOGLE_API_KEY')--if not api_key:- raise ValueError('GOOGLE_API_KEY is not set')--llm = ChatGoogle(model='gemini-2.0-flash', api_key=api_key)---async def main():- # Create browser profile with settings- browser_profile = BrowserProfile(- headless=False,- viewport=ViewportSize(width=1502, height=853),- ignore_https_errors=True,- )-- # Create browser session- browser_session = BrowserSession(- browser_profile=browser_profile,- )-- # Start the browser- await browser_session.start()-- agent = Agent(- browser_session=browser_session,- task='Go to https://browser-use.com/',- llm=llm,- )-- try:- result = await agent.run()- print(f'First task was {"successful" if result.is_successful else "not successful"}')-- if not result.is_successful:- raise RuntimeError('Failed to navigate to the initial page.')-- agent.add_new_task('Navigate to the documentation page')-- result = await agent.run()- print(f'Second task was {"successful" if result.is_successful else "not successful"}')-- if not result.is_successful:- raise RuntimeError('Failed to navigate to the documentation page.')-- while True:- next_task = input('Write your next task or leave empty to exit\n> ')-- if not next_task.strip():- print('Exiting...')- break-- agent.add_new_task(next_task)- result = await agent.run()-- print(f"Task '{next_task}' was {'successful' if result.is_successful else 'not successful'}")-- if not result.is_successful:- print('Failed to complete the task. Please try again.')- continue-- finally:- # Stop the browser session- await browser_session.stop()---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/features/outsource_state.py b/examples/features/outsource_state.pydeleted file mode 100644index 0c286c5c4..000000000--- a/examples/features/outsource_state.py+++ /dev/null@@ -1,64 +0,0 @@-"""-Show how to use custom outputs.--@dev You need to add OPENAI_API_KEY to your environment variables.-"""--import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--import anyio--from browser_use import Agent-from browser_use.agent.views import AgentState-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.llm import ChatOpenAI---async def main():- task = 'Go to hackernews show hn and give me the first 5 posts'-- browser_profile = BrowserProfile(- headless=True,- )- browser_session = BrowserSession(browser_profile=browser_profile)-- agent_state = AgentState()-- for i in range(10):- agent = Agent(- task=task,- llm=ChatOpenAI(model='gpt-4.1-mini'),- browser_session=browser_session,- injected_agent_state=agent_state,- page_extraction_llm=ChatOpenAI(model='gpt-4.1-mini'),- )-- done, valid = await agent.take_step()- print(f'Step {i}: Done: {done}, Valid: {valid}')-- if done and valid:- break-- # Save state to file- async with await anyio.open_file('agent_state.json', 'w') as f:- serialized = agent_state.model_dump_json(exclude={'history'})- await f.write(serialized)-- # Load state back from file- async with await anyio.open_file('agent_state.json', 'r') as f:- loaded_json = await f.read()- agent_state = AgentState.model_validate_json(loaded_json)-- break---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/features/parallel_agents.py b/examples/features/parallel_agents.pyindex 58f3177d3..c2964ad27 100644--- a/examples/features/parallel_agents.py+++ b/examples/features/parallel_agents.py@@ -23,6 +23,7 @@ browser_session = BrowserSession(llm = ChatOpenAI(model='gpt-4.1-mini')+# NOTE: This is experimental - you will have multiple agents running in the same browser sessionasync def main():await browser_session.start()agents = [@@ -31,8 +32,8 @@ async def main():'Search Google for weather in Tokyo','Check Reddit front page title','Look up Bitcoin price on Coinbase',- 'Find NASA image of the day',- 'Check top story on CNN',+ # 'Find NASA image of the day',+ # 'Check top story on CNN',# 'Search latest SpaceX launch date',# 'Look up population of Paris',# 'Find current time in Sydney',diff --git a/examples/features/pause_agent.py b/examples/features/pause_agent.pydeleted file mode 100644index dc7148c99..000000000--- a/examples/features/pause_agent.py+++ /dev/null@@ -1,101 +0,0 @@-import asyncio-import os-import sys-import threading--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from browser_use import Agent, ChatOpenAI---class AgentController:- def __init__(self):- llm = ChatOpenAI(model='gpt-4.1-mini')- self.agent = Agent(- task='open in one action https://www.google.com, https://www.wikipedia.org, https://www.youtube.com, https://www.github.com, https://amazon.com',- llm=llm,- )- self.running = False-- async def run_agent(self):- """Run the agent"""- self.running = True- await self.agent.run()-- def start(self):- """Start the agent in a separate thread"""- loop = asyncio.new_event_loop()- asyncio.set_event_loop(loop)- loop.run_until_complete(self.run_agent())-- def pause(self):- """Pause the agent"""- self.agent.pause()-- def resume(self):- """Resume the agent"""- self.agent.resume()-- def stop(self):- """Stop the agent"""- self.agent.stop()- self.running = False---def print_menu():- print('\nAgent Control Menu:')- print('1. Start')- print('2. Pause')- print('3. Resume')- print('4. Stop')- print('5. Exit')---async def main():- controller = AgentController()- agent_thread = None-- while True:- print_menu()- try:- choice = input('Enter your choice (1-5): ')- except KeyboardInterrupt:- choice = '5'-- if choice == '1' and not agent_thread:- print('Starting agent...')- agent_thread = threading.Thread(target=controller.start)- agent_thread.start()-- elif choice == '2':- print('Pausing agent...')- controller.pause()-- elif choice == '3':- print('Resuming agent...')- controller.resume()-- elif choice == '4':- print('Stopping agent...')- controller.stop()- if agent_thread:- agent_thread.join()- agent_thread = None-- elif choice == '5':- print('Exiting...')- if controller.running:- controller.stop()- if agent_thread:- agent_thread.join()- break-- await asyncio.sleep(0.1) # Small delay to prevent CPU spinning---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/features/planner.py b/examples/features/planner.pydeleted file mode 100644index 91c63ba78..000000000--- a/examples/features/planner.py+++ /dev/null@@ -1,28 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from browser_use import Agent, ChatOpenAI--llm = ChatOpenAI(model='gpt-4.1', temperature=0.0)-planner_llm = ChatOpenAI(- model='o3-mini',-)-task = 'your task'---agent = Agent(task=task, llm=llm, planner_llm=planner_llm, use_vision_for_planner=False, planner_interval=1)---async def main():- await agent.run()---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/features/result_processing.py b/examples/features/process_agent_output.pysimilarity index 100%rename from examples/features/result_processing.pyrename to examples/features/process_agent_output.pydiff --git a/examples/features/restrict_urls.py b/examples/features/restrict_urls.pyindex f995097f3..912fa5da7 100644--- a/examples/features/restrict_urls.py+++ b/examples/features/restrict_urls.py@@ -12,7 +12,7 @@ from browser_use import Agentfrom browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.llm import ChatOpenAI-llm = ChatOpenAI(model='gpt-4.1', temperature=0.0)+llm = ChatOpenAI(model='gpt-4.1-mini')task = ("go to google.com and search for openai.com and click on the first link then extract content and scroll down - what's there?")diff --git a/examples/features/save_trace.py b/examples/features/save_trace.pydeleted file mode 100644index 7dbe82375..000000000--- a/examples/features/save_trace.py+++ /dev/null@@ -1,38 +0,0 @@-import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from browser_use.agent.service import Agent-from browser_use.browser import BrowserProfile, BrowserSession-from browser_use.llm import ChatOpenAI--llm = ChatOpenAI(model='gpt-4.1', temperature=0.0)---async def main():- browser_session = BrowserSession(- browser_profile=BrowserProfile(- traces_dir='./tmp/traces/',- user_data_dir='~/.config/browseruse/profiles/default',- )- )-- await browser_session.start()- try:- agent = Agent(- task='Go to hackernews, then go to apple.com and return all titles of open tabs',- llm=llm,- browser_session=browser_session,- )- await agent.run()- finally:- await browser_session.stop()---asyncio.run(main())diff --git a/examples/features/small_model_for_extraction.py b/examples/features/small_model_for_extraction.pyindex 6d44a2ff2..3b18c0e77 100644--- a/examples/features/small_model_for_extraction.py+++ b/examples/features/small_model_for_extraction.py@@ -10,8 +10,11 @@ load_dotenv()from browser_use import Agent, ChatOpenAI-llm = ChatOpenAI(model='gpt-4.1', temperature=0.0)-small_llm = ChatOpenAI(model='gpt-4.1-mini', temperature=0.0)+# This uses a bigger model for the planning+# And a smaller model for the page content extraction+# THink of it like a subagent which only task is to extract content from the current page+llm = ChatOpenAI(model='gpt-4.1')+small_llm = ChatOpenAI(model='gpt-4.1-mini')task = 'Find the founders of browser-use in ycombinator, extract all links and open the links one by one'agent = Agent(task=task, llm=llm, page_extraction_llm=small_llm)diff --git a/examples/features/validate_output.py b/examples/features/validate_output.pydeleted file mode 100644index 31ffed812..000000000--- a/examples/features/validate_output.py+++ /dev/null@@ -1,49 +0,0 @@-"""-Demonstrate output validator.--@dev You need to add OPENAI_API_KEY to your environment variables.-"""--import asyncio-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from dotenv import load_dotenv--load_dotenv()--from pydantic import BaseModel--from browser_use import ActionResult, Agent, Controller-from browser_use.llm import ChatOpenAI--controller = Controller()---class DoneResult(BaseModel):- title: str- comments: str- hours_since_start: int---# we overwrite done() in this example to demonstrate the validator[email protected]('Done with task', param_model=DoneResult)-async def done(params: DoneResult):- result = ActionResult(is_done=True, extracted_content=params.model_dump_json())- print(result)- # NOTE: this is clearly wrong - to demonstrate the validator- return 'blablabla'---async def main():- task = 'Go to hackernews hn and give me the top 1 post'- model = ChatOpenAI(model='gpt-4.1-mini')- agent = Agent(task=task, llm=model, controller=controller, validate_output=True)- # NOTE: this should fail to demonstrate the validator- await agent.run(max_steps=5)---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/file_system/excel_sheet.py b/examples/file_system/excel_sheet.pyindex e0164c998..3f80cfe93 100644--- a/examples/file_system/excel_sheet.py+++ b/examples/file_system/excel_sheet.py@@ -9,20 +9,10 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from dotenv import load_dotenvload_dotenv()-from lmnr import Laminar--try:- Laminar.initialize(project_api_key=os.getenv('LMNR_PROJECT_API_KEY'))-except Exception:- passfrom browser_use import Agent-# Initialize the model-llm = ChatOpenAI(- model='o4-mini',- temperature=1.0,-)+llm = ChatOpenAI(model='o4-mini')task = (