Browser-Use Tutorial: AI-Powered Browser Automation with LLM Agents
Introduction
Browser-Use is an open-source Python library that enables Large Language Models (LLMs) to autonomously control web browsers. With Browser-Use, you can build AI agents capable of navigating web pages, filling forms, extracting data, and executing complex browser tasks just like a human would.
This library bridges the gap between LLM reasoning capabilities and real-world interaction through browsers. Unlike traditional web scraping that requires fragile CSS selectors or XPath expressions, Browser-Use leverages the vision and reasoning capabilities of LLMs to understand web pages both visually and semantically.
Popular use cases for Browser-Use include:
- Web Research Agent: Automatically search and gather information from multiple sources
- Form Automation: Fill web forms automatically
- Testing Agent: Perform automated UI testing
- Data Extraction: Extract structured data from web pages
- Workflow Automation: Automate multi-step workflows involving browser interactions
In this tutorial, we'll cover installation, basic usage, advanced techniques, and best practices for building reliable AI browser agents with Browser-Use.
Installation
Prerequisites
Before installing Browser-Use, make sure you have:
- Python 3.11 or newer
- pip or uv as your package manager
- An API key from an LLM provider (OpenAI, Anthropic, or others)
Installation with pip
pip install browser-use
Installation with uv (Recommended)
uv pip install browser-use
Install Playwright Browser
Browser-Use uses Playwright as its browser engine. After installation, run:
playwright install chromium
Setup Environment Variables
Create a .env file in your project root:
OPENAIAPIKEY=sk-your-openai-key
ANTHROPICAPIKEY=sk-ant-your-anthropic-key
Verify Installation
import browseruse
print(f"Browser-Use version: {browser
use.version}")
Basic Usage
Your First Agent
Here's the simplest example to create a browser agent:
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def main():
agent = Agent(
task="Search for today's Bitcoin price on Google and provide the result",
llm=ChatOpenAI(model="gpt-4o"),
)
result = await agent.run()
print(result)
asyncio.run(main())
The agent will open a browser, navigate to Google, search for the Bitcoin price, and return the result.
Using Anthropic Claude
Browser-Use supports various LLM providers. Here's an example using Claude:
import asyncio
from browseruse import Agent
from langchainanthropic import ChatAnthropic
async def main():
agent = Agent(
task="Open Wikipedia and search for information about Machine Learning",
llm=ChatAnthropic(model="claude-sonnet-4-20250514"),
)
result = await agent.run()
print(result)
asyncio.run(main())
Running with Visible Browser
By default, the browser runs in headless mode. To see what the agent is doing:
import asyncio
from browseruse import Agent, Browser, BrowserConfig
from langchainopenai import ChatOpenAI
async def main():
browser = Browser(
config=BrowserConfig(
headless=False, # Browser is visible
)
)
agent = Agent(
task="Navigate to GitHub and search for the browser-use repository",
llm=ChatOpenAI(model="gpt-4o"),
browser=browser,
)
result = await agent.run()
print(result)
await browser.close()
asyncio.run(main())
Extracting Structured Data
Use Pydantic models to get structured output:
import asyncio
from pydantic import BaseModel
from browseruse import Agent
from langchainopenai import ChatOpenAI
class ProductInfo(BaseModel):
name: str
price: str
rating: str
description: str
async def main():
agent = Agent(
task="Open amazon.com and search for the most popular gaming laptop. Get the first product's information.",
llm=ChatOpenAI(model="gpt-4o"),
returntype=ProductInfo,
)
result = await agent.run()
print(f"Name: {result.name}")
print(f"Price: {result.price}")
print(f"Rating: {result.rating}")
asyncio.run(main())
Advanced Usage
Custom Actions
You can add custom actions that can be called by the agent:
import asyncio
from browseruse import Agent, Controller
from langchainopenai import ChatOpenAI
controller = Controller()
@controller.action("Save data to CSV file")
def savetocsv(data: str, filename: str):
"""Save extracted data to a CSV file"""
import csv
rows = [row.split(",") for row in data.strip().split("\n")]
with open(filename, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
return f"Data successfully saved to {filename}"
@controller.action("Send notification")
def sendnotification(message: str):
"""Send a notification when the task is complete"""
print(f"NOTIFICATION: {message}")
return "Notification sent"
async def main():
agent = Agent(
task="""
Open amazon.com and search for Lenovo laptop prices.
Get the top 5 products with their names and prices.
Save them to a CSV file named 'laptopprices.csv'.
Send a notification that the task is complete.
""",
llm=ChatOpenAI(model="gpt-4o"),
controller=controller,
)
result = await agent.run()
print(result)
asyncio.run(main())
Browser Context and Session Management
For tasks that require login or state management:
import asyncio
from browseruse import Agent, Browser, BrowserConfig, BrowserContextConfig
from langchainopenai import ChatOpenAI
async def main():
browser = Browser(
config=BrowserConfig(
headless=False,
chromeinstancepath="/usr/bin/google-chrome",
)
)
contextconfig = BrowserContextConfig(
cookiesfile="cookies.json",
waitfornetworkidlepageloadtime=3.0,
browserwindowsize={"width": 1280, "height": 720},
locale="en-US",
timezoneid="America/NewYork",
)
context = await browser.newcontext(config=contextconfig)
agent = Agent(
task="Login to the dashboard and download the monthly report",
llm=ChatOpenAI(model="gpt-4o"),
browsercontext=context,
)
result = await agent.run()
await browser.close()
asyncio.run(main())
Multi-Tab Navigation
Agents can work with multiple tabs simultaneously:
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def main():
agent = Agent(
task="""
Open the first tab to google.com and search for "Python tutorial"
Open a new tab to stackoverflow.com and search for "Python best practices"
Compare results from both sources
Provide a combined summary from both sources
""",
llm=ChatOpenAI(model="gpt-4o"),
maxactionsperstep=5,
)
result = await agent.run()
print(result)
asyncio.run(main())
Handling Captcha and Anti-Bot Protection
For sites with anti-bot protection:
import asyncio
from browseruse import Agent, Browser, BrowserConfig
from langchainopenai import ChatOpenAI
async def main():
browser = Browser(
config=BrowserConfig(
headless=False,
disablesecurity=False,
extrachromiumargs=[
"--disable-blink-features=AutomationControlled",
],
)
)
agent = Agent(
task="Navigate to the target site and extract the required data",
llm=ChatOpenAI(model="gpt-4o"),
browser=browser,
maxfailures=5,
retrydelay=2,
)
result = await agent.run()
await browser.close()
asyncio.run(main())
Agent with Memory and History
Use message history to provide additional context:
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
from langchaincore.messages import HumanMessage, SystemMessage
async def main():
systemmessage = SystemMessage(
content="""You are a thorough research assistant.
Always verify information from at least 2 different sources.
Provide clear and structured answers."""
)
agent = Agent(
task="""
Research AI trends in Southeast Asia in 2026:
Search for recent articles about AI adoption in ASEAN companies
Find statistical data on AI usage in the region
Create a summary of findings
""",
llm=ChatOpenAI(model="gpt-4o"),
systempromptclass=None,
messagecontext=[systemmessage],
maxactionsperstep=3,
)
result = await agent.run(maxsteps=25)
print(result)
asyncio.run(main())
Parallel Agent Execution
Run multiple agents concurrently for efficiency:
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def researchtopic(topic: str):
agent = Agent(
task=f"Search for the latest information about {topic} and create a brief summary",
llm=ChatOpenAI(model="gpt-4o"),
)
return await agent.run()
async def main():
topics = [
"latest LLM developments",
"AI agent frameworks 2026",
"computer vision trends",
]
results = await asyncio.gather(
[researchtopic(topic) for topic in topics]
)
for topic, result in zip(topics, results):
print(f"\n{'='50}")
print(f"Topic: {topic}")
print(f"Result: {result}")
asyncio.run(main())
File Download Integration
import asyncio
from browseruse import Agent, Browser, BrowserConfig, BrowserContextConfig
from langchainopenai import ChatOpenAI
async def main():
contextconfig = BrowserContextConfig(
savedownloadspath="./downloads",
)
browser = Browser(config=BrowserConfig(headless=False))
context = await browser.newcontext(config=contextconfig)
agent = Agent(
task="""
Open the GitHub releases page for the browser-use project.
Download the source code zip from the latest release.
""",
llm=ChatOpenAI(model="gpt-4o"),
browsercontext=context,
)
result = await agent.run()
await browser.close()
asyncio.run(main())
Configuration and Tuning
Important Agent Parameters
agent = Agent(
task="Your task here",
llm=ChatOpenAI(model="gpt-4o"),
maxactionsperstep=10,
usevision=True,
maxfailures=3,
retrydelay=1,
toolcallingmethod="auto",
maxinputtokens=128000,
generategif=True,
)
Parameter descriptions:
| Parameter | Default | Description |
|-----------|---------|-------------|
| maxactionsperstep | 10 | Maximum actions per step |
| usevision | True | Use screenshots to understand pages |
| maxfailures | 3 | Failure tolerance before stopping |
| retrydelay | 1 | Delay (seconds) between retries |
| generategif | False | Generate GIF recording of agent actions |
| maxinputtokens | 128000 | Input token limit for LLM |
BrowserConfig Options
config = BrowserConfig(
headless=True,
disablesecurity=False,
extrachromiumargs=["--no-sandbox"],
chromeinstancepath=None,
wssurl=None,
proxy={
"server": "http://proxy:8080",
"username": "user",
"password": "pass",
},
)
Best Practices
1. Write Clear Task Descriptions
# Poor
agent = Agent(task="Find data", llm=llm)
Better
agent = Agent(
task="""
Open the Bureau of Labor Statistics website (bls.gov) and find
the US inflation data for January-June 2026. Note the monthly
and year-on-year inflation figures. If data is unavailable,
note it as N/A.
""",
llm=llm,
)
2. Use Proper Error Handling
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def main():
agent = Agent(
task="A task that might fail",
llm=ChatOpenAI(model="gpt-4o"),
maxfailures=5,
)
try:
result = await agent.run(maxsteps=30)
if result:
print(f"Success: {result}")
else:
print("Agent finished without results")
except Exception as e:
print(f"Error: {e}")
asyncio.run(main())
3. Optimize Token Usage
agent = Agent(
task="Your task",
llm=ChatOpenAI(model="gpt-4o"),
usevision=False, # Disable if vision isn't needed
maxactionsperstep=3, # Limit actions per step
maxinputtokens=64000, # Limit context window
)
4. Use Logging for Debugging
import logging
logging.basicConfig(level=logging.DEBUG)
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def main():
agent = Agent(
task="Task with detailed logging",
llm=ChatOpenAI(model="gpt-4o"),
generategif=True, # Record actions as GIF
)
result = await agent.run()
print(result)
asyncio.run(main())
5. Always Close the Browser
import asyncio
from browseruse import Agent, Browser, BrowserConfig
from langchainopenai import ChatOpenAI
async def main():
browser = Browser(config=BrowserConfig(headless=True))
try:
agent = Agent(
task="Your task",
llm=ChatOpenAI(model="gpt-4o"),
browser=browser,
)
result = await agent.run()
print(result)
finally:
await browser.close()
asyncio.run(main())
6. Scope Your Tasks Appropriately
Break large tasks into smaller sub-tasks:
import asyncio
from browseruse import Agent
from langchainopenai import ChatOpenAI
async def step1search():
agent = Agent(
task="Open Google and search for 'top Python libraries 2026'. Note the top 5 results.",
llm=ChatOpenAI(model="gpt-4o"),
)
return await agent.run()
async def step2detail(libraryname: str):
agent = Agent(
task=f"Open PyPI and search for the library {libraryname}. Note the latest version, download count, and brief description.",
llm=ChatOpenAI(model="gpt-4o"),
)
return await agent.run()
async def main():
searchresults = await step1search()
print(f"Search results: {searchresults}")
asyncio.run(main())
7. Security Considerations
- Never hardcode credentials in your code
- Use environment variables for API keys
- Be careful with sites that have strict terms of service
- Monitor LLM token usage for cost control
- Never use
disable_security=Truein production
Comparison with Similar Tools
| Feature | Browser-Use | Playwright (Manual) | Selenium |
|---------|-------------|--------------------:|----------|
| AI-Powered | Yes | No | No |
| Setup Complexity | Low | Medium | High |
| Adaptive to UI changes | Yes | No | No |
| Requires CSS/XPath selectors | No | Yes | Yes |
| Operational cost | LLM API cost | Free | Free |
| Suited for dynamic tasks | Yes | No | No |
Conclusion
Browser-Use opens a new paradigm in browser automation. Instead of writing fragile scripts with CSS selectors, you simply describe the task in natural language and let the LLM handle navigation and interaction.
Key takeaways from this tutorial:
pip install browser-use and playwright install chromiumTo get started, try creating a simple agent that searches for information on the web. Once you're comfortable, explore advanced features like custom actions and parallel agents to build more complex automation workflows.
Visit the Browser-Use GitHub repository for complete documentation and additional examples. Happy automating!