Skip to content

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

add: apply_to_job.py, buy_groceries.py, and phone_comparison.py

ShawnPana31e9650449a8
diff --git a/examples/use-cases/apply_to_job.py b/examples/use-cases/apply_to_job.py
new file mode 100644
index 000000000..77e6973f9
--- /dev/null
+++ b/examples/use-cases/apply_to_job.py
@@ -0,0 +1,120 @@
+import asyncio
+import os
+from dotenv import load_dotenv
+from browser_use import ActionResult, Agent, Browser, ChatOpenAI, ChatAnthropic, ChatGoogle, Tools
+from browser_use.tools.views import UploadFileAction
+import json
+
+load_dotenv()
+
+async def apply_to_rochester_regional_health(info: dict, llm: str, resume_path: str):
+ """
+ json format:
+ {
+ "first_name": "John",
+ "last_name": "Doe",
+ "email": "[email protected]",
+ "phone": "555-555-5555",
+ "age": "21",
+ "US_citizen": boolean,
+ "sponsorship_needed": boolean,
+
+ "resume": "Link to resume",
+ "postal_code": "12345",
+ "country": "USA",
+ "city": "Rochester",
+ "address": "123 Main St",
+
+ "gender": "Male",
+ "race": "Asian",
+ "Veteran_status": "Not a veteran",
+ "disability_status": "No disability"
+ }
+ """
+
+ tools = Tools()
+
+ @tools.action(description='Upload resume file')
+ async def upload_resume(browser_session):
+ params = UploadFileAction(
+ path=resume_path
+ )
+ return "Ready to upload resume"
+
+ browser = Browser(
+ cross_origin_iframes=True
+ )
+
+ task = f"""
+ - Your goal is to fill out and submit a job application form with the provided information.
+ - Navigate to https://apply.appcast.io/jobs/50590620606/applyboard/apply/
+ - Scroll through the entire application and use extract_structured_data action to extract all the relevant information needed to fill out the job application form. use this information and return a structured output that can be used to fill out the entire form: {info}. Use the done action to finish the task. Fill out the job application form with the following information.
+ - Before completing every step, refer to this information for accuracy. It is structured in a way to help you fill out the form and is the source of truth.
+ - Follow these instructions carefully:
+ - if anything pops up that blocks the form, close it out and continue filling out the form.
+ - Do not skip any fields, even if they are optional. If you do not have the information, make your best guess based on the information provided.
+ Fill out the form from top to bottom, never skip a field to come back to it later. When filling out a field, only focus on one field per step. For each of these steps, scroll to the related text. These are the steps:
+ 1) use input_text action to fill out the following:
+ - "First name"
+ - "Last name"
+ - "Email"
+ - "Phone number"
+ 2) use the upload_file_to_element action to fill out the following:
+ - Resume upload field
+ 3) use input_text action to fill out the following:
+ - "Postal code"
+ - "Country"
+ - "State"
+ - "City"
+ - "Address"
+ - "Age"
+ 4) use click_element_by_index action to select the following options:
+ - "Are you legally authorized to work in the country for which you are applying?"
+ - "Will you now or in the future require sponsorship for employment visa status (e.g., H-1B visa status, etc.) to work legally for Rochester Regional Health?"
+ - "Do you have, or are you in the process of obtaining, a professional license?"
+ - SELECT NO FOR THIS FIELD
+ 5) use input_text action to fill out the following:
+ - "What drew you to healthcare?"
+ 6) use click_element_by_index action to select the following options:
+ - "How many years of experience do you have in a related role?"
+ - "Gender"
+ - "Race"
+ - "Hispanic/Latino"
+ - "Veteran status"
+ - "Disability status"
+ 7) use input_text action to fill out the following:
+ - "Today's date"
+ 8) CLICK THE SUBMIT BUTTON AND CHECK FOR A SUCCESS SCREEN. Once there is a success screen, complete your end task of writing final_result and outputting it.
+ - Before you start, create a step-by-step plan to complete the entire task. make sure the delegate a step for each field to be filled out.
+ *** IMPORTANT ***:
+ - You are not done until you have filled out every field of the form.
+ - When you have completed the entire form, press the submit button to submit the application and use the done action once you have confirmed that the application is submitted
+ - PLACE AN EMPHASIS ON STEP 4, the click_element_by_index action. That section should be filled out.
+ - At the end of the task, structure your final_result as 1) a human-readable summary of all detections and actions performed on the page with 2) a list with all questions encountered in the page. Do not say "see above." Include a fully written out, human-readable summary at the very end.
+ """
+
+ available_file_paths = [resume_path]
+
+ agent = Agent(
+ task=task,
+ llm=llm,
+ browser=browser,
+ tools=tools,
+ available_file_paths=available_file_paths,
+ )
+
+ history = await agent.run()
+
+ return history.final_result()
+
+async def main():
+ llm = ChatOpenAI(model="o3")
+
+ with open('mock/test_data.json') as f:
+ mock_info = json.load(f)
+
+ results = await apply_to_rochester_regional_health(mock_info, llm, resume_path="mock/test_CV.pdf")
+ print("Search Results:", results)
+
+if __name__ == '__main__':
+ asyncio.run(main())
diff --git a/examples/use-cases/buy_groceries.py b/examples/use-cases/buy_groceries.py
new file mode 100644
index 000000000..a787cd010
--- /dev/null
+++ b/examples/use-cases/buy_groceries.py
@@ -0,0 +1,66 @@
+import asyncio
+from browser_use import Agent, Browser, ChatBrowserUse
+from model import GroceryCart
+from typing import List
+
+async def add_to_cart(items: List[str] = ["milk", "eggs", "bread"]):
+ browser = Browser(
+ cdp_url="http://localhost:9222"
+ )
+
+ llm = ChatBrowserUse()
+
+ # Task prompt
+ task = f"""
+ Search for "{items}" on Instacart at the nearest store.
+
+ You will buy all of the items at the same store.
+ For each item:
+ 1. Search for the item
+ 2. Find the best match (closest name, lowest price)
+ 3. Add the item to the cart
+
+ Site:
+ - Instacart: https://www.instacart.com/
+ """
+
+ # Create agent with structured output
+ agent = Agent(
+ browser=browser,
+ llm=llm,
+ task=task,
+ output_model_schema=GroceryCart,
+ )
+
+ # Run the agent
+ result = await agent.run()
+ return result
+
+if __name__ == "__main__":
+ # Get user input
+ items_input = input("What items would you like to add to cart (comma-separated)? ").strip()
+ if not items_input:
+ items = ["milk", "eggs", "bread"]
+ print(f"Using default items: {items}")
+ else:
+ items = [item.strip() for item in items_input.split(",")]
+
+ result = asyncio.run(add_to_cart(items))
+
+ # Access structured output
+ if result and result.structured_output:
+ cart = result.structured_output
+
+ print(f"\n{'='*60}")
+ print(f"Items Added to Cart")
+ print(f"{'='*60}\n")
+
+ for item in cart.items:
+ print(f"Name: {item.name}")
+ print(f"Price: ${item.price}")
+ if item.brand:
+ print(f"Brand: {item.brand}")
+ if item.size:
+ print(f"Size: {item.size}")
+ print(f"URL: {item.url}")
+ print(f"{'-'*60}")
diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.py
deleted file mode 100644
index da302ae65..000000000
--- a/examples/use-cases/find_and_apply_to_jobs.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""
-Goal: Searches for job listings, evaluates relevance based on a CV, and applies
-
-@dev You need to add OPENAI_API_KEY to your environment variables.
-Also you have to install PyPDF2 to read pdf files: pip install PyPDF2
-"""
-
-import asyncio
-import csv
-import logging
-import os
-import sys
-from pathlib import 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 pydantic import BaseModel
-from PyPDF2 import PdfReader # type: ignore
-
-from browser_use import ActionResult, Agent, ChatOpenAI, Tools
-from browser_use.browser import BrowserProfile, BrowserSession
-
-required_env_vars = ['AZURE_OPENAI_KEY', 'AZURE_OPENAI_ENDPOINT']
-for var in required_env_vars:
- if not os.getenv(var):
- raise ValueError(f'{var} is not set. Please add it to your environment variables.')
-
-logger = logging.getLogger(__name__)
-# full screen mode
-tools = Tools()
-
-# NOTE: This is the path to your cv file
-# create a dummy cv
-CV = Path.cwd() / 'dummy_cv.pdf'
-with open(CV, 'w') as f:
- f.write('Hi I am a machine learning engineer with 3 years of experience in the field')
-
-logger.info(f'Using dummy cv at {CV}')
-
-
-class Job(BaseModel):
- title: str
- link: str
- company: str
- fit_score: float
- location: str | None = None
- salary: str | None = None
-
-
[email protected]('Save jobs to file - with a score how well it fits to my profile', param_model=Job)
-def save_jobs(job: Job):
- with open('jobs.csv', 'a', newline='') as f:
- writer = csv.writer(f)
- writer.writerow([job.title, job.company, job.link, job.salary, job.location])
-
- return 'Saved job to file'
-
-
[email protected]('Read jobs from file')
-def read_jobs():
- with open('jobs.csv') as f:
- return f.read()
-
-
[email protected]('Read my cv for context to fill forms')
-def read_cv():
- pdf = PdfReader(CV)
- text = ''
- for page in pdf.pages:
- text += page.extract_text() or ''
- logger.info(f'Read cv with {len(text)} characters')
- return ActionResult(extracted_content=text, include_in_memory=True)
-
-
- 'Upload cv to element - call this function to upload if element is not found, try with different index of the same upload element',
-)
-async def upload_cv(index: int, browser_session: BrowserSession):
- path = str(CV.absolute())
-
- # Get the element by index
- dom_element = await browser_session.get_element_by_index(index)
-
- if dom_element is None:
- logger.info(f'No element found at index {index}')
- return ActionResult(error=f'No element found at index {index}')
-
- # Check if it's a file input element
- if not browser_session.is_file_input(dom_element):
- logger.info(f'Element at index {index} is not a file upload element')
- return ActionResult(error=f'Element at index {index} is not a file upload element')
-
- try:
- # Dispatch upload file event with the file input element
- from browser_use.browser.events import UploadFileEvent
-
- event = browser_session.event_bus.dispatch(UploadFileEvent(node=dom_element, file_path=path))
- await event
- await event.event_result(raise_if_any=True, raise_if_none=False)
- msg = f'Successfully uploaded file "{path}" to index {index}'
- logger.info(msg)
- return ActionResult(extracted_content=msg)
- except Exception as e:
- logger.debug(f'Error in upload: {str(e)}')
- return ActionResult(error=f'Failed to upload file to index {index}')
-
-
-browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
- disable_security=True,
- user_data_dir='~/.config/browseruse/profiles/default',
- )
-)
-
-
-async def main():
- # ground_task = (
- # 'You are a professional job finder. '
- # '1. Read my cv with read_cv'
- # '2. Read the saved jobs file '
- # '3. start applying to the first link of Amazon '
- # 'You can navigate through pages e.g. by scrolling '
- # 'Make sure to be on the english version of the page'
- # )
- ground_task = (
- 'You are a professional job finder. '
- '1. Read my cv with read_cv'
- 'find ml internships in and save them to a file'
- 'search at company:'
- )
- tasks = [
- ground_task + '\n' + 'Google',
- # ground_task + '\n' + 'Amazon',
- # ground_task + '\n' + 'Apple',
- # ground_task + '\n' + 'Microsoft',
- # ground_task
- # + '\n'
- # + 'go to https://nvidia.wd5.myworkdayjobs.com/en-US/NVIDIAExternalCareerSite/job/Taiwan%2C-Remote/Fulfillment-Analyst---New-College-Graduate-2025_JR1988949/apply/autofillWithResume?workerSubType=0c40f6bd1d8f10adf6dae42e46d44a17&workerSubType=ab40a98049581037a3ada55b087049b7 NVIDIA',
- # ground_task + '\n' + 'Meta',
- ]
- model = ChatOpenAI(model='gpt-4.1-mini')
-
- agents = []
- for task in tasks:
- agent = Agent(task=task, llm=model, tools=tools, browser_session=browser_session)
- agents.append(agent)
-
- await asyncio.gather(*[agent.run() for agent in agents])
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/use-cases/phone_comparison.py b/examples/use-cases/phone_comparison.py
new file mode 100644
index 000000000..21417803a
--- /dev/null
+++ b/examples/use-cases/phone_comparison.py
@@ -0,0 +1,72 @@
+import asyncio
+from browser_use import Agent, Browser, ChatBrowserUse
+from model import PriceComparison
+
+async def find(item: str = "Used iPhone 12"):
+ """
+ Search for an item across multiple marketplaces and compare prices.
+
+ Args:
+ item: The item to search for (e.g., "Used iPhone 12")
+
+ Returns:
+ PriceComparison object with structured results
+ """
+ browser = Browser(
+ cdp_url="http://localhost:9222"
+ )
+
+ llm = ChatBrowserUse()
+
+ # Task prompt
+ task = f"""
+ Search for "{item}" on eBay, Amazon, and Swappa. Get any 2-3 listings from each site.
+
+ For each site:
+ 1. Search for "{item}"
+ 2. Extract ANY 2-3 listings you find (sponsored, renewed, used - all are fine)
+ 3. Get: title, price (number only, if range use lower number), source, full URL, condition
+ 4. Move to next site
+
+ Sites:
+ - eBay: https://www.ebay.com/
+ - Amazon: https://www.amazon.com/
+ - Swappa: https://swappa.com/
+ """
+
+ # Create agent with structured output
+ agent = Agent(
+ browser=browser,
+ llm=llm,
+ task=task,
+ output_model_schema=PriceComparison,
+ )
+
+ # Run the agent
+ result = await agent.run()
+ return result
+
+if __name__ == "__main__":
+ # Get user input
+ query = input("What item would you like to compare prices for? ").strip()
+ if not query:
+ query = "Used iPhone 12"
+ print(f"Using default query: {query}")
+
+ result = asyncio.run(find(query))
+
+ # Access structured output
+ if result and result.structured_output:
+ comparison = result.structured_output
+
+ print(f"\n{'='*60}")
+ print(f"Price Comparison Results: {comparison.search_query}")
+ print(f"{'='*60}\n")
+
+ for listing in comparison.listings:
+ print(f"Title: {listing.title}")
+ print(f"Price: ${listing.price}")
+ print(f"Source: {listing.source}")
+ print(f"URL: {listing.url}")
+ print(f"Condition: {listing.condition or 'N/A'}")
+ print(f"{'-'*60}")