Skip to content

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

Use-cases examples

Magnus Müller3048375a16a5
diff --git a/examples/use-cases/scrolling_page.py b/examples/features/scrolling_page.py
similarity index 100%
rename from examples/use-cases/scrolling_page.py
rename to examples/features/scrolling_page.py
diff --git a/examples/use-cases/README.md b/examples/use-cases/README.md
deleted file mode 100644
index f45c0977a..000000000
--- a/examples/use-cases/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Use Cases of Browser-Use
-
-| File Name | Description |
-|-----------|------------|
-| `captcha.py` | Automates CAPTCHA solving on a demo website. |
-| `check_appointment.py` | Checks for available visa appointment slots on the Greece MFA website. |
-| `find_and_apply_to_jobs.py` | Searches for job listings, evaluates relevance based on a CV, and applies automatically. |
-| `online_coding_agent.py` | Implements a multi-agent system for online code editors, with separate agents for coding and execution. |
-| `post-twitter.py` | Provides a template for automated posting on X (Twitter), including new tweets, tagging, and replies. |
-| `scrolling_page.py` | Automates webpage scrolling with various scrolling actions and text search functionality. |
-| `twitter_post_using_cookies.py` | Automates posting on X (Twitter) using stored authentication cookies. |
-| `web_voyager_agent.py` | A general-purpose web navigation agent for tasks like flight booking and course searching. |
diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.py
deleted file mode 100644
index 84312c9da..000000000
--- a/examples/use-cases/google_sheets.py
+++ /dev/null
@@ -1,107 +0,0 @@
-import os
-import sys
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-import asyncio
-
-from dotenv import load_dotenv
-
-from browser_use import Agent, ChatOpenAI, Controller
-from browser_use.browser import BrowserProfile, BrowserSession
-
-# Load environment variables
-load_dotenv()
-if not os.getenv('OPENAI_API_KEY'):
- raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-
-# Use the default controller with built-in Google Sheets actions
-# The controller already includes all the necessary Google Sheets actions:
-# - select_cell_or_range: Select specific cells or ranges (Ctrl+G navigation)
-# - get_range_contents: Get contents of cells using clipboard
-# - get_sheet_contents: Get entire sheet contents
-# - clear_selected_range: Clear selected cells
-# - input_selected_cell_text: Input text into selected cells
-# - update_range_contents: Batch update ranges with TSV data
-controller = Controller()
-
-# For more Google Sheets keyboard shortcuts and automation ideas, see:
-# - https://github.com/philc/sheetkeys/blob/master/content_scripts/sheet_actions.js
-# - https://github.com/philc/sheetkeys/blob/master/content_scripts/commands.js
-# - https://support.google.com/docs/answer/181110?hl=en&co=GENIE.Platform%3DDesktop#zippy=%2Cmac-shortcuts
-
-# Tip: LLM is bad at spatial reasoning, don't make it navigate with arrow keys relative to current cell
-# if given arrow keys, it will try to jump from G1 to A2 by pressing Down, without realizing needs to go Down+LeftLeftLeftLeft
-
-
-async def main():
- browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- user_data_dir='~/.config/browseruse/profiles/default',
- keep_alive=True,
- ),
- )
-
- await browser_session.start()
- try:
- model = ChatOpenAI(model='gpt-4.1-mini')
-
- # eraser = Agent(
- # task="""
- # Clear all the existing values in columns A through M in this Google Sheet:
- # https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit
- # """,
- # llm=model,
- # browser_session=browser_session,
- # controller=controller,
- # )
- # await eraser.run()
-
- researcher = Agent(
- task="""
- Open this Google Sheet and read it to understand the structure: https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit
- Make sure column headers are present and all existing values in the sheet are formatted correctly.
- Columns should be labeled using the top row of cells:
- A: "Company Name"
- B: "CEO Full Name"
- C: "CEO Country of Birth"
- D: "Source URL where the information was found"
- Then Google to find the full name and nationality of each CEO of the top Fortune 100 companies and for each company,
- append a row to this existing Google Sheet. You can do a few searches at a time,
- but make sure to check the sheet for errors after inserting a new batch of rows.
- At the end, double check the formatting and structure and fix any issues by updating/overwriting cells.
- """,
- llm=model,
- browser_session=browser_session,
- controller=controller,
- )
- await researcher.run()
- finally:
- await browser_session.stop()
-
- # improvised_continuer = Agent(
- # task="""
- # Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit
- # Add 3 more rows to the bottom continuing the existing pattern, make sure any data you add is sourced correctly.
- # """,
- # llm=model,
- # browser_session=browser_session,
- # controller=controller,
- # )
- # await improvised_continuer.run()
-
- # final_fact_checker = Agent(
- # task="""
- # Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit
- # Fact-check every entry, add a new column F with your findings for each row.
- # Make sure to check the source URL for each row, and make sure the information is correct.
- # """,
- # llm=model,
- # browser_session=browser_session,
- # controller=controller,
- # )
- # await final_fact_checker.run()
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/online_coding_agent.py b/examples/use-cases/online_coding_agent.py
deleted file mode 100644
index 49327a41e..000000000
--- a/examples/use-cases/online_coding_agent.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# Goal: Implements a multi-agent system for online code editors, with separate agents for coding and execution.
-
-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
-from browser_use.browser import BrowserSession
-
-if not os.getenv('OPENAI_API_KEY'):
- raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-
-
-async def main():
- browser_session = BrowserSession()
- model = ChatOpenAI(model='gpt-4.1-mini')
-
- # Initialize browser agent
- agent1 = Agent(
- task='Open an online code editor programiz.',
- llm=model,
- browser_session=browser_session,
- )
- executor = Agent(
- task='Executor. Execute the code written by the coder and suggest some updates if there are errors.',
- llm=model,
- browser_session=browser_session,
- )
-
- coder = Agent(
- task='Coder. Your job is to write and complete code. You are an expert coder. Code a simple calculator. Write the code on the coding interface after agent1 has opened the link.',
- llm=model,
- browser_session=browser_session,
- )
- await agent1.run()
- await executor.run()
- await coder.run()
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/play_chess.py b/examples/use-cases/play_chess.py
deleted file mode 100755
index efa725e1c..000000000
--- a/examples/use-cases/play_chess.py
+++ /dev/null
@@ -1,432 +0,0 @@
-#!/usr/bin/env -S uv run --script
-# /// script
-# requires-python = ">=3.11"
-# dependencies = ["python-chess", "browser-use", "beautifulsoup4"]
-# ///
-
-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 asyncio
-import logging
-
-import chess # type: ignore
-from bs4 import BeautifulSoup
-from pydantic import BaseModel, Field
-
-from browser_use import Agent, ChatOpenAI, Controller
-from browser_use.agent.views import ActionResult
-from browser_use.browser import BrowserSession
-
-if not os.getenv('OPENAI_API_KEY'):
- raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-
-logger = logging.getLogger(__name__)
-
-controller = Controller()
-
-
-class PlayMoveParams(BaseModel):
- move: str = Field(
- description="The move in Standard Algebraic Notation (SAN) exactly as provided in the 'Legal Moves' list (e.g., 'Nf3', 'e4', 'Qh7#')."
- )
-
-
-FILES = 'abcdefgh'
-RANKS = '87654321'
-
-
-# --- Helper Functions ---
-def to_px(val: float) -> str:
- """Convert float to px string, e.g. 42.0 -> '42px'."""
- s = f'{val:.1f}'.rstrip('0').rstrip('.')
- return f'{s}px'
-
-
-def from_px(px: str) -> float:
- """Convert px string to float, e.g. '42px' -> 42.0."""
- return float(px.replace('px', '').strip())
-
-
-def parse_transform(style: str) -> tuple[float, float] | None:
- """Extracts x and y pixel coordinates from a CSS transform string."""
- try:
- parts = style.split('(')[1].split(')')[0].split(',')
- x_px_str = float(parts[0].strip().replace('px', ''))
- y_px_str = float(parts[1].strip().replace('px', ''))
- return x_px_str, y_px_str
- except Exception as e:
- logger.error(f'Error parsing transform style: {e}')
- return None
-
-
-def algebraic_to_pixels(square: str, square_size: float) -> tuple[str, str]:
- """Converts algebraic notation to Lichess pixel coordinates using dynamic size."""
- file_char = square[0].lower()
- rank_char = square[1]
-
- if file_char not in FILES or rank_char not in RANKS:
- raise ValueError(f'Invalid square: {square}')
-
- x_index = FILES.index(file_char)
- y_index = RANKS.index(rank_char)
-
- x_px = x_index * square_size
- y_px = y_index * square_size
- return to_px(x_px), to_px(y_px)
-
-
-def pixels_to_algebraic(x_px: float, y_px: float, square_size: float) -> str:
- """Converts Lichess pixel coordinates to algebraic notation using dynamic size."""
- if not square_size:
- raise ValueError('Square size cannot be zero or None.')
-
- x_index = int(round(x_px / square_size))
- y_index = int(round(y_px / square_size))
-
- if 0 <= x_index < 8 and 0 <= y_index < 8:
- return f'{FILES[x_index]}{RANKS[y_index]}'
-
- raise ValueError(f'Pixel coordinates out of bounds: ({x_px}, {y_px})')
-
-
-async def calculate_square_size(browser: BrowserSession) -> float | None:
- """Dynamically calculates the size of a chess square in pixels."""
- try:
- if not browser.agent_focus:
- return None
-
- # Get board HTML using CDP
- result = await browser.agent_focus.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': "document.querySelector('cg-board') ? document.querySelector('cg-board').innerHTML : null",
- 'returnByValue': True,
- },
- session_id=browser.agent_focus.session_id,
- )
- board_html = result.get('result', {}).get('value')
- if not board_html:
- raise ValueError('Failed to get board HTML')
- soup = BeautifulSoup(board_html, 'html.parser')
- pieces = soup.find_all('piece')
- if not pieces:
- raise ValueError('No pieces found.')
- x_coords: set[float] = set()
- for piece in pieces:
- if hasattr(piece, 'get'):
- style = piece.get('style') # type: ignore
- else:
- continue
- if style:
- coords = parse_transform(style) # type: ignore
- if coords:
- x_coords.add(coords[0])
-
- sorted_x = sorted(list(x_coords))
- x_diffs = [sorted_x[i] - sorted_x[i - 1] for i in range(1, len(sorted_x))]
- square_size = round(min(d for d in x_diffs if d > 1), 1)
- logger.debug(f'Calculated square size: {square_size}px')
- return square_size
- except Exception as e:
- logger.error(f'Error calculating square size: {e}')
- return None
-
-
-def get_piece_symbol(class_list: list[str]) -> str:
- color = class_list[0]
- ptype = class_list[1]
- symbols = {'king': 'k', 'queen': 'q', 'rook': 'r', 'bishop': 'b', 'knight': 'n', 'pawn': 'p'}
- symbol = symbols.get(ptype, '?')
- return symbol.upper() if color == 'white' else symbol
-
-
-def create_fen_board(board_state: dict) -> str:
- fen = ''
- for rank_num in RANKS:
- empty_count = 0
- for file_char in FILES:
- square = f'{file_char}{rank_num}'
- if square in board_state:
- if empty_count > 0:
- fen += str(empty_count)
- empty_count = 0
- fen += board_state[square]
- else:
- empty_count += 1
- if empty_count > 0:
- fen += str(empty_count)
- if rank_num != RANKS[-1]:
- fen += '/'
- return fen
-
-
-async def get_current_board_info(browser: BrowserSession) -> tuple[str | None, float | None]:
- """Reads the current board HTML and returns FEN string and square size."""
- board_state = {}
- board_html = ''
- square_size = None
-
- try:
- if not browser.agent_focus:
- return None, None
-
- # Get board HTML using CDP
- result = await browser.agent_focus.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': "document.querySelector('cg-board') ? document.querySelector('cg-board').innerHTML : null",
- 'returnByValue': True,
- },
- session_id=browser.agent_focus.session_id,
- )
- board_html = result.get('result', {}).get('value')
- square_size = await calculate_square_size(browser)
- except Exception as e:
- logger.error(f'Error (get_info): Could not read cg-board: {e}')
- return None, None
-
- if not board_html or not square_size:
- return None, None
-
- soup = BeautifulSoup(board_html, 'html.parser')
- pieces = soup.find_all('piece')
- for piece in pieces:
- if not hasattr(piece, 'get'):
- continue
- style = piece.get('style') # type: ignore
- class_ = piece.get('class') # type: ignore
-
- if style and class_:
- coords = parse_transform(style) # type: ignore
- if coords:
- x_px, y_px = coords
- try:
- square = pixels_to_algebraic(x_px, y_px, square_size)
- board_state[square] = get_piece_symbol(class_) # type: ignore
- except ValueError as ve:
- logger.error(f'Error: {ve}')
-
- if not board_state or not square_size:
- return None, None
-
- fen_board = create_fen_board(board_state)
- full_fen = f'{fen_board} w KQkq - 0 1'
- return full_fen, square_size
-
-
-# --- Custom Actions ---
- 'Read Chess Board',
-)
-async def read_board(browser: BrowserSession):
- """Reads the board, returns FEN and legal moves in SAN (+/#), and the last move by opponent if possible."""
- # Get the current page's CDP session
- if not browser.agent_focus:
- return ActionResult(extracted_content='No active page to read board from.')
-
- full_fen, _ = await get_current_board_info(browser)
-
- if not full_fen:
- return ActionResult(extracted_content='Could not read board state.')
-
- legal_moves_descriptive = []
- last_move_san = None
-
- try:
- if browser.agent_focus:
- result = await browser.agent_focus.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': "document.querySelector('l4x') ? document.querySelector('l4x').innerHTML : null",
- 'returnByValue': True,
- },
- session_id=browser.agent_focus.session_id,
- )
- move_list_html = result.get('result', {}).get('value') or ''
- soup = BeautifulSoup(move_list_html, 'html.parser')
- move_tags = soup.find_all('kwdb')
- moves = [tag.get_text(strip=True) for tag in move_tags]
- last_move_san = moves[-1] if moves else None
- except Exception as e:
- logger.error(f'Error extracting move list: {e}')
- last_move_san = None
-
- try:
- board = chess.Board(full_fen)
- for move in board.legal_moves:
- san = board.san(move)
- board.push(move)
- is_mate = board.is_checkmate()
- board.pop()
- is_check = board.gives_check(move) and not is_mate
-
- move_str_out = san.replace('+', '')
- if is_mate:
- move_str_out += '#'
- elif is_check:
- move_str_out += '+'
- legal_moves_descriptive.append(move_str_out)
-
- except Exception as chess_err:
- logger.error(f'Error generating SAN moves: {chess_err}. FEN: {full_fen}')
- legal_moves_descriptive = ['Error']
-
- result_text = f'FEN: {full_fen}. Legal Moves (SAN): {", ".join(legal_moves_descriptive)}'
- if last_move_san:
- result_text = f'Last move: {last_move_san}. {result_text}'
- logger.info(f'Read board result: {result_text}')
- return ActionResult(extracted_content=result_text, include_in_memory=True)
-
-
- 'Play Chess Move',
- param_model=PlayMoveParams,
-)
-async def play_move(params: PlayMoveParams, browser: BrowserSession):
- """Plays a chess move given in SAN by converting it to UCI and clicking."""
- san_move = params.move.strip()
- uci_move = ''
-
- try:
- current_fen, square_size = await get_current_board_info(browser)
- if not current_fen or square_size is None:
- return ActionResult(extracted_content='Failed to get current FEN or square size to play move.')
-
- board = chess.Board(current_fen)
- san_to_parse = san_move.replace('#', '').replace('+', '')
- move_obj = board.parse_san(san_to_parse)
- uci_move = move_obj.uci()
-
- except Exception as e:
- return ActionResult(extracted_content=f"Could not parse SAN move '{san_move}' or get FEN: {e}")
-
- start_sq = uci_move[:2]
- end_sq = uci_move[2:]
-
- try:
- start_x_str, start_y_str = algebraic_to_pixels(start_sq, square_size)
- end_x_str, end_y_str = algebraic_to_pixels(end_sq, square_size)
- start_x = from_px(start_x_str)
- start_y = from_px(start_y_str)
- end_x = from_px(end_x_str)
- end_y = from_px(end_y_str)
- except Exception as e:
- return ActionResult(extracted_content=f"Could not convert UCI '{uci_move}' to coordinates: {e}")
-
- try:
- if not browser.agent_focus:
- return ActionResult(extracted_content='No active page to play move on.')
-
- click_offset = square_size / 2
- start_click_x = start_x + click_offset
- start_click_y = start_y + click_offset
- end_click_x = end_x + click_offset
- end_click_y = end_y + click_offset
-
- logger.debug(f"DEBUG: Playing SAN '{san_move}' (UCI: {uci_move}).")
-
- # Get board element bounds first
- result = await browser.agent_focus.cdp_client.send.Runtime.evaluate(
- params={
- 'expression': """
- const board = document.querySelector('cg-board');
- if (board) {
- const rect = board.getBoundingClientRect();
- {x: rect.left, y: rect.top, width: rect.width, height: rect.height};
- } else {
- null;
- }
- """,
- 'returnByValue': True,
- },
- session_id=browser.agent_focus.session_id,
- )
- board_rect = result.get('result', {}).get('value')
-
- if not board_rect:
- return ActionResult(extracted_content='Could not find chess board element.')
-
- # Click start position
- await browser.agent_focus.cdp_client.send.Input.dispatchMouseEvent(
- params={
- 'type': 'mousePressed',
- 'x': board_rect['x'] + start_click_x,
- 'y': board_rect['y'] + start_click_y,
- 'button': 'left',
- 'clickCount': 1,
- },
- session_id=browser.agent_focus.session_id,
- )
- await browser.agent_focus.cdp_client.send.Input.dispatchMouseEvent(
- params={
- 'type': 'mouseReleased',
- 'x': board_rect['x'] + start_click_x,
- 'y': board_rect['y'] + start_click_y,
- 'button': 'left',
- },
- session_id=browser.agent_focus.session_id,
- )
-
- await asyncio.sleep(0.5)
-
- # Click end position
- await browser.agent_focus.cdp_client.send.Input.dispatchMouseEvent(
- params={
- 'type': 'mousePressed',
- 'x': board_rect['x'] + end_click_x,
- 'y': board_rect['y'] + end_click_y,
- 'button': 'left',
- 'clickCount': 1,
- },
- session_id=browser.agent_focus.session_id,
- )
- await browser.agent_focus.cdp_client.send.Input.dispatchMouseEvent(
- params={
- 'type': 'mouseReleased',
- 'x': board_rect['x'] + end_click_x,
- 'y': board_rect['y'] + end_click_y,
- 'button': 'left',
- },
- session_id=browser.agent_focus.session_id,
- )
- await asyncio.sleep(0.5)
- return ActionResult(extracted_content=f'Played move {san_move}.', include_in_memory=True)
-
- except Exception as e:
- error_message = f'Failed to play move {san_move} using Coordinates: {e}'
- logger.error(f'ERROR: {error_message}')
- return ActionResult(extracted_content=error_message)
-
-
-# --- Main Execution ---
-async def main():
- agent = Agent(
- task="""
- Objective: Play chess against the computer on Lichess and win.
-
- Strategy: Play the Queen's Gambit opening (1. d4 d5 2. c4) as White. Aim for a solid, strategic game.
-
- Instructions:
- 1. Open lichess.org.
- 2. Find and click the button or link with the text "Play with the computer". Use a standard click action.
- 3. On the setup screen, ensure 'White' is selected. Click the "Play" or "Start game" button.
- 4. Use 'Read Chess Board'. This will provide the FEN and a list called 'Legal Moves (SAN)'.
- 5. The 'Legal Moves (SAN)' list will contain moves like 'Nf3' (Knight to f3), 'e4' (pawn to e4), 'O-O' (kingside castle), 'Rxe4+' (Rook captures on e4, giving check), or 'Qh7#' (Queen to h7, checkmate).
- 6. Analyze the FEN, moves, and **you MUST choose your next move EXACTLY as it appears in the 'Legal Moves (SAN)' list.** Do not invent moves or use any other format.
- 7. Use the 'Play Chess Move' action, passing the exact SAN string you chose. For example: `play_move(move='Nf3')` or `play_move(move='Rxe4+')`.
- 8. Repeat steps 4-7 until the game ends. If anything seems wrong, use 'Read Chess Board' again.
- 9. Announce the final result.
- """,
- llm=ChatOpenAI(model='gpt-4.1-mini'),
- controller=controller,
- )
- result = await agent.run()
- logger.info(result)
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.py
deleted file mode 100644
index bc529adae..000000000
--- a/examples/use-cases/post-twitter.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""
-Goal: Provides a template for automated posting on X (Twitter), including new tweets, tagging, and replies.
-
-X Posting Template using browser-use
-----------------------------------------
-
-This template allows you to automate posting on X using browser-use.
-It supports:
-- Posting new tweets
-- Tagging users
-- Replying to tweets
-
-Add your target user and message in the config section.
-
-target_user="XXXXX"
-message="XXXXX"
-reply_url="XXXXX"
-
-Any issues, contact me on X @defichemist95
-"""
-
-import asyncio
-import os
-import sys
-from dataclasses import dataclass
-
-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, Controller
-from browser_use.browser import BrowserProfile, BrowserSession
-
-if not os.getenv('OPENAI_API_KEY'):
- raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')
-
-
-# ============ Configuration Section ============
-@dataclass
-class TwitterConfig:
- """Configuration for Twitter posting"""
-
- openai_api_key: str
- chrome_path: str
- target_user: str # Twitter handle without @
- message: str
- reply_url: str
- headless: bool = False
- model: str = 'gpt-4.1-mini'
- base_url: str = 'https://x.com/home'
-
-
-# Customize these settings
-openai_key = os.getenv('OPENAI_API_KEY')
-assert openai_key is not None, 'OPENAI_API_KEY must be set'
-
-config = TwitterConfig(
- openai_api_key=openai_key,
- chrome_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # This is for MacOS (Chrome)
- target_user='XXXXX',
- message='XXXXX',
- reply_url='XXXXX',
- headless=False,
-)
-
-
-def create_twitter_agent(config: TwitterConfig) -> Agent:
- llm = ChatOpenAI(model=config.model, api_key=config.openai_api_key)
-
- browser_profile = BrowserProfile(
- headless=config.headless,
- executable_path=config.chrome_path,
- )
- browser_session = BrowserSession(browser_profile=browser_profile)
-
- controller = Controller()
-
- # Construct the full message with tag
- full_message = f'@{config.target_user} {config.message}'
-
- # Create the agent with detailed instructions
- agent = Agent(
- task=f"""Navigate to Twitter and create a post and reply to a tweet.
-
- Here are the specific steps:
-
- 1. Go to {config.base_url}. See the text input field at the top of the page that says "What's happening?"
- 2. Look for the text input field at the top of the page that says "What's happening?"
- 3. Click the input field and type exactly this message:
- "{full_message}"
- 4. Find and click the "Post" button (look for attributes: 'button' and 'data-testid="tweetButton"')
- 5. Do not click on the '+' button which will add another tweet.
-
- 6. Navigate to {config.reply_url}
- 7. Before replying, understand the context of the tweet by scrolling down and reading the comments.
- 8. Reply to the tweet under 50 characters.
-
- Important:
- - Wait for each element to load before interacting
- - Make sure the message is typed exactly as shown
- - Verify the post button is clickable before clicking
- - Do not click on the '+' button which will add another tweet
- """,
- llm=llm,
- controller=controller,
- browser_session=browser_session,
- )
- return agent
-
-
-async def post_tweet(agent: Agent):
- try:
- await agent.run(max_steps=100)
- print('Tweet posted successfully!')
- except Exception as e:
- print(f'Error posting tweet: {str(e)}')
-
-
-async def main():
- agent = create_twitter_agent(config)
- await agent.run()
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.py
index 7ccde8bf2..4c10fd381 100644
--- a/examples/use-cases/shopping.py
+++ b/examples/use-cases/shopping.py
@@ -9,7 +9,6 @@ from dotenv import load_dotenv
load_dotenv()
from browser_use import Agent, ChatOpenAI
-from browser_use.browser import BrowserSession
task = """
### Prompt for Shopping Agent – Migros Online Grocery Order
@@ -108,19 +107,13 @@ At this stage, check the basket on the top right (indicates the price) and check
**Important:** Ensure efficiency and accuracy throughout the process."""
-browser_session = BrowserSession()
-agent = Agent(
- task=task,
- llm=ChatOpenAI(model='gpt-4.1-mini'),
- browser_session=browser_session,
-)
+agent = Agent(task=task, llm=ChatOpenAI(model='gpt-4.1-mini'))
async def main():
await agent.run()
input('Press Enter to close the browser...')
- await browser_session.kill()
if __name__ == '__main__':
diff --git a/examples/use-cases/test_cv.txt b/examples/use-cases/test_cv.txt
deleted file mode 100644
index 190a18037..000000000
--- a/examples/use-cases/test_cv.txt
+++ /dev/null
@@ -1 +0,0 @@
-123
diff --git a/examples/use-cases/twitter_cookies.txt b/examples/use-cases/twitter_cookies.txt
deleted file mode 100644
index 804318b75..000000000
--- a/examples/use-cases/twitter_cookies.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-[{
- "name": "auth_token",
- "value": "auth_token_cookie_value",
- "domain": ".x.com",
- "path": "/"
- },
-{
- "name": "ct0",
- "value": "ct0_cookie_value",
- "domain": ".x.com",
- "path": "/"
-}]
diff --git a/examples/use-cases/twitter_post_using_cookies.py b/examples/use-cases/twitter_post_using_cookies.py
index 3bf999975..8c674a9cb 100644
--- a/examples/use-cases/twitter_post_using_cookies.py
+++ b/examples/use-cases/twitter_post_using_cookies.py
@@ -25,7 +25,6 @@ llm = ChatGoogle(model='gemini-2.0-flash-exp', api_key=api_key)
browser_session = BrowserSession(
browser_profile=BrowserProfile(
user_data_dir='~/.config/browseruse/profiles/default',
- # headless=False, # Uncomment to see the browser
# executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
)
)
diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.py
deleted file mode 100644
index 74d678460..000000000
--- a/examples/use-cases/web_voyager_agent.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# Goal: A general-purpose web navigation agent for tasks like flight booking and course searching.
-
-import asyncio
-import os
-import sys
-
-# Adjust Python path
-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 ChatAzureOpenAI, ChatOpenAI
-
-# Set LLM based on defined environment variables
-if os.getenv('OPENAI_API_KEY'):
- llm = ChatOpenAI(
- model='gpt-4.1',
- )
-elif os.getenv('AZURE_OPENAI_KEY') and os.getenv('AZURE_OPENAI_ENDPOINT'):
- llm = ChatAzureOpenAI(
- model='gpt-4.1',
- )
-else:
- raise ValueError('No LLM found. Please set OPENAI_API_KEY or AZURE_OPENAI_KEY and AZURE_OPENAI_ENDPOINT.')
-
-
-browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=False, # This is True in production
- minimum_wait_page_load_time=1, # 3 on prod
- maximum_wait_page_load_time=10, # 20 on prod
- viewport={'width': 1280, 'height': 1100},
- user_data_dir='~/.config/browseruse/profiles/default',
- # trace_path='./tmp/web_voyager_agent',
- )
-)
-
-# TASK = """
-# Find the lowest-priced one-way flight from Cairo to Montreal on February 21, 2025, including the total travel time and number of stops. on https://www.google.com/travel/flights/
-# """
-# TASK = """
-# Browse Coursera, which universities offer Master of Advanced Study in Engineering degrees? Tell me what is the latest application deadline for this degree? on https://www.coursera.org/"""
-TASK = """
-Find and book a hotel in Paris with suitable accommodations for a family of four (two adults and two children) offering free cancellation for the dates of February 14-21, 2025. on https://www.booking.com/
-"""
-
-
-async def main():
- agent = Agent(
- task=TASK,
- llm=llm,
- browser_session=browser_session,
- validate_output=True,
- enable_memory=False,
- )
- history = await agent.run(max_steps=50)
- history.save_to_file('./tmp/history.json')
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/wikipedia_banana_to_quantum.py b/examples/use-cases/wikipedia_banana_to_quantum.py
deleted file mode 100644
index 88fcaf265..000000000
--- a/examples/use-cases/wikipedia_banana_to_quantum.py
+++ /dev/null
@@ -1,36 +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
-from browser_use.browser import BrowserProfile, BrowserSession
-
-# video https://preview.screen.studio/share/vuq91Ej8
-llm = ChatOpenAI(
- model='gpt-4.1',
- temperature=0.0,
-)
-task = 'go to https://en.wikipedia.org/wiki/Banana and click on buttons on the wikipedia page to go as fast as possible from banna to Quantum mechanics'
-
-browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- viewport_expansion=-1,
- highlight_elements=False,
- user_data_dir='~/.config/browseruse/profiles/default',
- ),
-)
-agent = Agent(task=task, llm=llm, browser_session=browser_session, use_vision=False)
-
-
-async def main():
- await agent.run()
-
-
-if __name__ == '__main__':
- asyncio.run(main())