Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战

Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战

一、概述

Browser-use 是一个旨在将 AI “智能体”(Agents)与真实浏览器进行交互的 Python 库,可以轻松实现浏览器自动化。在配合 LLM(如 GPT 系列)使用时,浏览器-use 能够让你的智能体发起对网页的访问、操作页面元素、收集信息、执行脚本等,从而扩展 AI 应用的落地场景。

目前 Browser-use 最低需要 Python 3.11 及以上,才能正常使用其封装的 Playwright 功能。

1. 技术栈:

  • LangChain(AI Agent框架)
  • Playwright(浏览器自动化)
  • dotenv(环境变量 key)
  • 异步I/O架构

2. 流程图

Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战

browser-use:语言模型 -> 决策/控制 -> 浏览器执行 -> 数据回传 -> 模型后处理


二、核心特性

1. 简单的 Agent 接口

通过 Agent 类即可快速创建带浏览器交互能力的智能体,赋能 LLM 与网页之间的复杂操作。

agent = Agent(         task="打开 https://cn.vuejs.org/guide/essentials/computed,获取页面里所有的 h2 标签文本及所有的 a 标签文本(以及它的 href)",         llm=llm,     ) result = await agent.run() 

2. 多语言模型支持

可轻松集成 LangChain 提供的各类 LLM(如 OpenAI、Anthropic、Cohere 等)进行高级任务管理。

模型 所属/类型
GPT-4o OpenAI
Claude Anthropic
Azure Azure OpenAI
Gemini Google Generative AI
DeepSeek-V3 DeepSeek
DeepSeek-R1 DeepSeek
Ollama 本地模型 (需安装 Ollama)

3. 基于 Playwright

默认使用 Playwright 进行浏览器的无头启动、页面操作和渲染控制;对常见网页交互场景提供友好的抽象。

4. 云端版 & 本地版

除了本地安装运行外,Browser-use 也提供托管版本,可以直接在云端执行,无需配置本地环境。


三、安装与环境配置

1. Python 版本

  • 需要 Python 3.11 或更高版本。
  • 推荐在独立虚拟环境(venv)或管理工具(如 uv)中配置环境。

1.1. 推荐使用 pyenv 管理 python

Github:https://github.com/pyenv/pyenv

brew install pyenv pyenv install 3.11.9 
# pyenv 根目录 export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH"  # 初始化 eval "$(pyenv init -)" 

Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战

2. 安装方法

2.1. 安装 browser-use

pip3 install browser-use 

2.2. 安装 Playwright

playwright install 
  • 此操作会自动下载 Chromium 无头浏览器,用于后续的浏览器自动化。

2.3. 配置 LLM API Keys(可选)

  • 在 .env 文件中填写相应的 OPENAI_API_KEY=、ANTHROPIC_API_KEY= 等 Key。
OPENAI_API_KEY=sk-xxxxxxx 
  • 如果使用其他 LLM,需要参考 LangChain 文档或对应服务提供的说明进行配置。

四、基础配置

1. Agent

1.1. Agent 参数

参数名称 类型 默认值 说明
task str 代理需要执行的任务描述。(必传)
llm BaseChatModel (LangChain Model) 主语言模型,执行对话和工具调用。(必传)
controller Controller 实例 默认
Controller
自定义函数/工具调用的注册表
use_vision bool True 是否启用视觉能力(截图+分析)。如模型支持图像输入,可显著提高网页理解;也会产生额外 token 成本。
Deepseek 需要设置为 False
save_conversation_path str 若指定,则会将对话历史保存在该路径下,用于调试或审计。
system_prompt_class type (自定义 System Prompt 类) 默认Prompt 自定义系统提示词逻辑
browser Browser (Browser-use 实例) 重用已创建的 Browser 实例;若不提供,则 Agent 每次 run() 时会自动创建并关闭新的浏览器。
browser_context BrowserContext (Playwright 实例) 使用已有的浏览器上下文 (Context)。适合需要维护持久会话 (cookies/localStorage) 的场景。
max_steps int 100 允许 Agent 执行的最大步骤数,防止死循环或无限操作。
planner_llm BaseChatModel __ 规划用语言模型,与主 LLM 分开;可用较小/便宜模型处理高层策略。
use_vision_for_planner bool True Planner 是否能使用视觉功能(若主 LLM 已开启视觉,这里可独立关闭以节省资源)。
planner_interval int 1 Planner 模型执行间隔。即每多少步调用一次 Planner 作重新规划。
message_context str 额外的任务/上下文信息,辅助 LLM 更好理解或执行任务。
+ 03/28 文档已删除字段
initial_actions list[dict] 初始化时要执行的动作列表(无需经 LLM 调用),格式为 {action_name: {...}}。
max_actions_per_step int 10 每个步骤里可执行的最大动作数,用于控制 Agent 过度频繁操作。
max_failures int 3 允许 Agent 失败的最大次数,超过则停止任务。
retry_delay int (秒) 10 当遇到限流 (rate limit) 或可重试的错误时,等待多少秒后再次尝试。
generate_gif bool 或 str (路径) False 是否录制浏览器过程生成 GIF。为 True 时自动生成随机文件名;为字符串时将 GIF 存储到该路径。

1.2. Agent 执行流程图

Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战

2. Browser 配置

Browser-use 提供两个主要配置类:

  • BrowserConfig:控制浏览器整体行为
  • BrowserContextConfig:控制单个上下文(浏览器标签页/会话)的行为

官方推荐:「1 个 Agent 对应 1 个 Browser 和 1 个 Context」,以增强稳定性和开发体验。

2.1. BrowserConfig

from browser_use import BrowserConfig  config = BrowserConfig(     headless=False,     disable_security=True ) browser = Browser(config=config) 
参数名称 类型 默认值 说明
headless bool False 是否启用无头模式(不显示 UI)
disable_security bool True 是否禁用浏览器安全功能(如跨域限制)
extra_browser_args list[str] [] 启动浏览器时的额外参数
proxy dict / str 设置代理,遵循 Playwright 规范
new_context_config BrowserContextConfig 新建 默认的新上下文配置
wss_url str WebSocket 连接地址,连接云端浏览器服务(如 browserbase、steel.dev)
cdp_url str Chrome DevTools 协议地址,连接本地 Chrome 实例
chrome_instance_path str 指定本地 Chrome 安装路径,保留登录状态和 Cookie
关闭所有正在运行的 Chrome

2.2. BrowserContextConfig 配置

from browser_use.browser.context import BrowserContextConfig  config = BrowserContextConfig(     cookies_file="path/to/cookies.json",     wait_for_network_idle_page_load_time=3.0,     browser_window_size={'width': 1280, 'height': 1100},     locale='en-US',     user_agent='Mozilla/5.0...',     highlight_elements=True,     viewport_expansion=500,     allowed_domains=['google.com', 'wikipedia.org'], ) 
参数名称 类型 默认值 说明
minimum_wait_page_load_time float 0.5 捕获网页状态前的最小等待时间
wait_for_network_idle_page_load_time float 1.0 等待网络空闲时间,可提高到 3-5s 以兼容慢速网站
maximum_wait_page_load_time float 5.0 页面加载的最长等待时间
browser_window_size dict 浏览器窗口大小,适配大多数 UI 和横幅
locale str 设置语言/地区(如 zh-CN, en-GB),影响语言头和格式
user_agent str 自定义浏览器 User-Agent
highlight_elements bool True 是否高亮交互元素(调试用)
viewport_expansion int 500 页面内容扩展范围(像素),影响哪些元素被 LLM 看到。-1 为全部,0 为仅视口内
allowed_domains list[str] 限制代理访问的域名,若为空则不限制
cookies_file str 加载持久化 Cookie 文件
save_recording_path str 保存操作录像的目录路径
trace_path str 保存 Trace 文件目录,命名为 {trace_path}/{context_id}.zip

3. 输出内容

3.1. History 方法

方法 说明
urls() 访问过的 URL 列表
screenshots() 截图路径列表
action_names() 执行的动作名称
extracted_content() 抽取到的内容
errors() 执行中出现的错误
model_actions() 所有动作及参数
final_result() 最终结果
is_done() 是否成功完成
has_errors() 是否有错误
model_thoughts() LLM 推理过程
action_results() 所有动作结果

3.2. 示例

from pydantic import BaseModel from typing import List from dotenv import load_dotenv from browser_use import Agent, Controller from langchain_openai import ChatOpenAI import asyncio  # Define the output format as a Pydantic model class Post(BaseModel): 	post_title: str 	post_url: str   class Posts(BaseModel): 	posts: List[Post]   load_dotenv() controller = Controller(output_model=Posts)   async def main(): 	task = '从掘金获取 Vue / React / AI 相关文章' 	model = ChatOpenAI(model='gpt-4o') 	agent = Agent(task=task, llm=model, controller=controller) 	history = await agent.run() 	result = history.final_result() 	print('result--->', result) 	print('history.urls()--->', history.urls()) 	# print('history.screenshots()--->', history.screenshots()) 	print('history.action_names()--->', history.action_names()) 	print('history.extracted_content()--->', history.extracted_content()) 	print('history.errors()--->', history.errors()) 	print('history.model_actions()--->', history.model_actions()) 	print('history.is_done()--->', history.is_done()) 	print('history.has_errors()--->', history.has_errors()) 	print('history.model_thoughts()--->', history.model_thoughts()) 	print('history.action_results()--->', history.action_results()) 	if result: 		parsed: Posts = Posts.model_validate_json(result)  		for post in parsed.posts: 			print('n--------------------------------') 			print(f'Title:            {post.post_title}') 			print(f'URL:              {post.post_url}') 	else: 		print('No result')   if __name__ == '__main__': 	asyncio.run(main()) 
result---> {"posts": [{"post_title": "vue3.5+deepseek+arco+markdownu642du5efawebu7248u6d41u5f0fu8f93u51faAIu6a21u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "ud83dude80ud83dude80ud83dude80u5c24u96e8u6eaau8fdeu53d1u4e24u6761u63a8u7279u5899u88c2u63a8u8350u7684u8fd9u4e9bu5e93u4f60u4e00u5b9au8981u77e5u9053uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "u524du7aefu4f6cu4eecuff01u584cu623fu4e86uff01u7528u8fc7Element-Plusu7684u8fdbu6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "u548cu540eu7aefu5927u6218u4e09u767eu56deu5408u540euff0cu5351u5faeu524du7aefu8fd8u662fu9009u62e9u4e86u81eau5df1u5199excelu5bfcu51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "u4ece DeepSeek u770b25u5e74u524du7aefu7684u4e00u4e2au5c0fu8d8bu52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "ud83dude80ud83dude80ud83dude80u5c24u96e8u6eaau8fdeu53d1u4e24u6761u63a8u7279u5899u88c2u63a8u8350u7684u8fd9u4e9bu5e93u4f60u4e00u5b9au8981u77e5u9053uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "u524du7aefu4f6cu4eecuff01u584cu623fu4e86uff01u7528u8fc7Element-Plusu7684u8fdbu6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "u548cu540eu7aefu5927u6218u4e09u767eu56deu5408u540euff0cu5351u5faeu524du7aefu8fd8u662fu9009u62e9u4e86u81eau5df1u5199excelu5bfcu51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "vue3.5+deepseek+arco+markdownu642du5efawebu7248u6d41u5f0fu8f93u51faAIu6a21u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "u4ece DeepSeek u770b25u5e74u524du7aefu7684u4e00u4e2au5c0fu8d8bu52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "u6709u4e86Traeuff0cu4ebau4ebau90fdu662fu7a0bu5e8fu5458u7684u65f6u4ee3u6765u4e86", "post_url": "https://juejin.cn/post/7463397212120973375"}, {"post_title": "u6b63u5f0fu5ba3u6218uff0cDeepSeek u9876u5f97u4f4fu5417uff1f", "post_url": "https://juejin.cn/post/7464848482987704329"}, {"post_title": "u7528 DeepSeek u6253u9020u4f60u7684u8d85u5f3au4ee3u7801u52a9u624b", "post_url": "https://juejin.cn/post/7454888708588945443"}, {"post_title": "u521au521auff0cDeepSeek u89e3u7b54u4e86u56f0u6270u6211u4e94u5e74u7684u6280u672fu95eeu9898u3002u65f6u4ee3u786eu5b9eu53d8u4e86uff01", "post_url": "https://juejin.cn/post/7472248441454018575"}, {"post_title": "u653eu5f03u6ca1u7528u7684u672cu5730u90e8u7f72u6b8bu8840u7248DeepSeeku5427uff0cu6559u4f60u5982u4f55u767du5ad6u6ee1u8840u7248DeepSeek", "post_url": "https://juejin.cn/post/7466832084486914083"}]} history.urls()---> ['about:blank', 'https://juejin.cn/', 'https://juejin.cn/', 'https://juejin.cn/', 'https://juejin.cn/', 'https://juejin.cn/', 'https://juejin.cn/', 'https://juejin.cn/'] history.action_names()---> ['go_to_url', 'input_text', 'click_element', 'extract_content', 'input_text', 'click_element', 'extract_content', 'input_text', 'click_element', 'extract_content', 'done'] history.extracted_content()---> ['🔗  Navigated to https://juejin.cn', '⌨️  Input Vue into index 11', '🖱️  Clicked button with index 11: ', '📄  Extracted from pagen: ```jsonn{n  "top_5_vue_articles": [n    {n      "post_title": "vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板",n      "post_url": "https://juejin.cn/post/7486369696738017321"n    },n    {n      "post_title": "🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!",n      "post_url": "https://juejin.cn/post/7484131071569772595"n    },n    {n      "post_title": "前端佬们!塌房了!用过Element-Plus的进来~",n      "post_url": "https://juejin.cn/post/7485966905418760227"n    },n    {n      "post_title": "和后端大战三百回合后,卑微前端还是选择了自己写excel导出",n      "post_url": "https://juejin.cn/post/7447368539936587776"n    },n    {n      "post_title": "从 DeepSeek 看25年前端的一个小趋势",n      "post_url": "https://juejin.cn/post/7468323178931879972"n    }n  ]n}n```n', '⌨️  Input React into index 11', '🖱️  Clicked button with index 11: ', '📄  Extracted from pagen: ```jsonn{n  "top_5_react_articles": [n    {n      "post_title": "🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!",n      "post_url": "/post/7484131071569772595"n    },n    {n      "post_title": "前端佬们!塌房了!用过Element-Plus的进来~",n      "post_url": "/post/7485966905418760227"n    },n    {n      "post_title": "和后端大战三百回合后,卑微前端还是选择了自己写excel导出",n      "post_url": "/post/7447368539936587776"n    },n    {n      "post_title": "vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板",n      "post_url": "/post/7486369696738017321"n    },n    {n      "post_title": "从 DeepSeek 看25年前端的一个小趋势",n      "post_url": "/post/7468323178931879972"n    }n  ]n}n```n', '⌨️  Input AI into index 11', '🖱️  Clicked button with index 11: ', '📄  Extracted from pagen: ```jsonn{n  "top_5_ai_articles": [n    {n      "post_title": "有了Trae,人人都是程序员的时代来了",n      "post_url": "/post/7463397212120973375"n    },n    {n      "post_title": "正式宣战,DeepSeek 顶得住吗?",n      "post_url": "/post/7464848482987704329"n    },n    {n      "post_title": "用 DeepSeek 打造你的超强代码助手",n      "post_url": "/post/7454888708588945443"n    },n    {n      "post_title": "刚刚,DeepSeek 解答了困扰我五年的技术问题。时代确实变了!",n      "post_url": "/post/7472248441454018575"n    },n    {n      "post_title": "放弃没用的本地部署残血版DeepSeek吧,教你如何白嫖满血版DeepSeek",n      "post_url": "/post/7466832084486914083"n    }n  ]n}n```n', '{"posts": [{"post_title": "vue3.5+deepseek+arco+markdown\u642d\u5efaweb\u7248\u6d41\u5f0f\u8f93\u51faAI\u6a21\u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "\ud83d\ude80\ud83d\ude80\ud83d\ude80\u5c24\u96e8\u6eaa\u8fde\u53d1\u4e24\u6761\u63a8\u7279\u5899\u88c2\u63a8\u8350\u7684\u8fd9\u4e9b\u5e93\u4f60\u4e00\u5b9a\u8981\u77e5\u9053\uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "\u524d\u7aef\u4f6c\u4eec\uff01\u584c\u623f\u4e86\uff01\u7528\u8fc7Element-Plus\u7684\u8fdb\u6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "\u548c\u540e\u7aef\u5927\u6218\u4e09\u767e\u56de\u5408\u540e\uff0c\u5351\u5fae\u524d\u7aef\u8fd8\u662f\u9009\u62e9\u4e86\u81ea\u5df1\u5199excel\u5bfc\u51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "\u4ece DeepSeek \u770b25\u5e74\u524d\u7aef\u7684\u4e00\u4e2a\u5c0f\u8d8b\u52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "\ud83d\ude80\ud83d\ude80\ud83d\ude80\u5c24\u96e8\u6eaa\u8fde\u53d1\u4e24\u6761\u63a8\u7279\u5899\u88c2\u63a8\u8350\u7684\u8fd9\u4e9b\u5e93\u4f60\u4e00\u5b9a\u8981\u77e5\u9053\uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "\u524d\u7aef\u4f6c\u4eec\uff01\u584c\u623f\u4e86\uff01\u7528\u8fc7Element-Plus\u7684\u8fdb\u6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "\u548c\u540e\u7aef\u5927\u6218\u4e09\u767e\u56de\u5408\u540e\uff0c\u5351\u5fae\u524d\u7aef\u8fd8\u662f\u9009\u62e9\u4e86\u81ea\u5df1\u5199excel\u5bfc\u51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "vue3.5+deepseek+arco+markdown\u642d\u5efaweb\u7248\u6d41\u5f0f\u8f93\u51faAI\u6a21\u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "\u4ece DeepSeek \u770b25\u5e74\u524d\u7aef\u7684\u4e00\u4e2a\u5c0f\u8d8b\u52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "\u6709\u4e86Trae\uff0c\u4eba\u4eba\u90fd\u662f\u7a0b\u5e8f\u5458\u7684\u65f6\u4ee3\u6765\u4e86", "post_url": "https://juejin.cn/post/7463397212120973375"}, {"post_title": "\u6b63\u5f0f\u5ba3\u6218\uff0cDeepSeek \u9876\u5f97\u4f4f\u5417\uff1f", "post_url": "https://juejin.cn/post/7464848482987704329"}, {"post_title": "\u7528 DeepSeek \u6253\u9020\u4f60\u7684\u8d85\u5f3a\u4ee3\u7801\u52a9\u624b", "post_url": "https://juejin.cn/post/7454888708588945443"}, {"post_title": "\u521a\u521a\uff0cDeepSeek \u89e3\u7b54\u4e86\u56f0\u6270\u6211\u4e94\u5e74\u7684\u6280\u672f\u95ee\u9898\u3002\u65f6\u4ee3\u786e\u5b9e\u53d8\u4e86\uff01", "post_url": "https://juejin.cn/post/7472248441454018575"}, {"post_title": "\u653e\u5f03\u6ca1\u7528\u7684\u672c\u5730\u90e8\u7f72\u6b8b\u8840\u7248DeepSeek\u5427\uff0c\u6559\u4f60\u5982\u4f55\u767d\u5ad6\u6ee1\u8840\u7248DeepSeek", "post_url": "https://juejin.cn/post/7466832084486914083"}]}'] history.errors()---> [None, None, None, None, None, None, None, None] history.model_actions()---> [{'go_to_url': {'url': 'https://juejin.cn'}, 'interacted_element': None}, {'input_text': {'index': 11, 'text': 'Vue'}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '探索稀土掘金', 'value': '', 'class': 'search-input', 'data-v-fdf9839c': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input[type="search"][placeholder="探索稀土掘金"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'click_element': {'index': 11}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '探索稀土掘金', 'value': '', 'class': 'search-input', 'data-v-fdf9839c': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input[type="search"][placeholder="探索稀土掘金"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'extract_content': {'goal': "Extract the top 5 articles for 'Vue' including post_title and post_url."}, 'interacted_element': None}, {'input_text': {'index': 11, 'text': 'React'}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '搜索文章/小册/标签/用户', 'value': '', 'class': 'search-input active', 'data-v-fdf9839c': '', 'style': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input.active[type="search"][placeholder="搜索文章/小册/标签/用户"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'click_element': {'index': 11}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '搜索文章/小册/标签/用户', 'value': '', 'class': 'search-input active', 'data-v-fdf9839c': '', 'style': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input.active[type="search"][placeholder="搜索文章/小册/标签/用户"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'extract_content': {'goal': "Extract the top 5 articles for 'React' including post_title and post_url."}, 'interacted_element': None}, {'input_text': {'index': 11, 'text': 'AI'}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '搜索文章/小册/标签/用户', 'value': '', 'class': 'search-input active', 'data-v-fdf9839c': '', 'style': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input.active[type="search"][placeholder="搜索文章/小册/标签/用户"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'click_element': {'index': 11}, 'interacted_element': DOMHistoryElement(tag_name='input', xpath='html/body/div/div/div/div/div/div/header/div/nav/ul/ul/li/ul/li/form/input', highlight_index=11, entire_parent_branch_path=['div', 'div', 'div', 'div', 'div', 'div', 'header', 'div', 'nav', 'ul', 'ul', 'li', 'ul', 'li', 'form', 'input'], attributes={'type': 'search', 'maxlength': '64', 'placeholder': '搜索文章/小册/标签/用户', 'value': '', 'class': 'search-input active', 'data-v-fdf9839c': '', 'style': ''}, shadow_root=False, css_selector='html > body > div > div > div > div > div > div > header > div > nav > ul > ul > li > ul > li > form > input.search-input.active[type="search"][placeholder="搜索文章/小册/标签/用户"]', page_coordinates=None, viewport_coordinates=None, viewport_info=None)}, {'extract_content': {'goal': "Extract the top 5 articles for 'AI' including post_title and post_url."}, 'interacted_element': None}, {'done': {'posts': [{'post_title': 'vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板', 'post_url': 'https://juejin.cn/post/7486369696738017321'}, {'post_title': '🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!', 'post_url': 'https://juejin.cn/post/7484131071569772595'}, {'post_title': '前端佬们!塌房了!用过Element-Plus的进来~', 'post_url': 'https://juejin.cn/post/7485966905418760227'}, {'post_title': '和后端大战三百回合后,卑微前端还是选择了自己写excel导出', 'post_url': 'https://juejin.cn/post/7447368539936587776'}, {'post_title': '从 DeepSeek 看25年前端的一个小趋势', 'post_url': 'https://juejin.cn/post/7468323178931879972'}, {'post_title': '🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!', 'post_url': 'https://juejin.cn/post/7484131071569772595'}, {'post_title': '前端佬们!塌房了!用过Element-Plus的进来~', 'post_url': 'https://juejin.cn/post/7485966905418760227'}, {'post_title': '和后端大战三百回合后,卑微前端还是选择了自己写excel导出', 'post_url': 'https://juejin.cn/post/7447368539936587776'}, {'post_title': 'vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板', 'post_url': 'https://juejin.cn/post/7486369696738017321'}, {'post_title': '从 DeepSeek 看25年前端的一个小趋势', 'post_url': 'https://juejin.cn/post/7468323178931879972'}, {'post_title': '有了Trae,人人都是程序员的时代来了', 'post_url': 'https://juejin.cn/post/7463397212120973375'}, {'post_title': '正式宣战,DeepSeek 顶得住吗?', 'post_url': 'https://juejin.cn/post/7464848482987704329'}, {'post_title': '用 DeepSeek 打造你的超强代码助手', 'post_url': 'https://juejin.cn/post/7454888708588945443'}, {'post_title': '刚刚,DeepSeek 解答了困扰我五年的技术问题。时代确实变了!', 'post_url': 'https://juejin.cn/post/7472248441454018575'}, {'post_title': '放弃没用的本地部署残血版DeepSeek吧,教你如何白嫖满血版DeepSeek', 'post_url': 'https://juejin.cn/post/7466832084486914083'}], 'success': True}, 'interacted_element': None}] history.is_done()---> True history.has_errors()---> False history.model_thoughts()---> [AgentBrain(evaluation_previous_goal='Unknown - No previous actions to evaluate.', memory="Starting the task. Need to open the Juejin website and search for 'Vue', 'React', and 'AI' keywords. Each search should yield at least 5 articles. Currently, 0 out of 3 keywords searched.", next_goal='Open the Juejin website.'), AgentBrain(evaluation_previous_goal='Success - Successfully navigated to the Juejin website.', memory="Task started. Currently, 0 out of 3 keywords searched ('Vue', 'React', 'AI'). Next, search for 'Vue' and extract the top 5 articles.", next_goal="Search for the keyword 'Vue' on Juejin."), AgentBrain(evaluation_previous_goal="Success - Successfully searched for the keyword 'Vue'.", memory="Task in progress. Searched for 'Vue' (1/3 keywords completed). Next, extract the top 5 articles for 'Vue'.", next_goal="Extract the top 5 articles for 'Vue'."), AgentBrain(evaluation_previous_goal="Success - Extracted the top 5 articles for 'Vue'.", memory="Task in progress. Searched for 'Vue' (1/3 keywords completed). Next, search for 'React' and extract the top 5 articles.", next_goal="Search for the keyword 'React' on Juejin."), AgentBrain(evaluation_previous_goal="Success - Successfully searched for the keyword 'React'.", memory="Task in progress. Searched for 'React' (2/3 keywords completed). Next, extract the top 5 articles for 'React'.", next_goal="Extract the top 5 articles for 'React'."), AgentBrain(evaluation_previous_goal="Success - Extracted the top 5 articles for 'React'.", memory="Task in progress. Searched for 'React' (2/3 keywords completed). Next, search for 'AI' and extract the top 5 articles.", next_goal="Search for the keyword 'AI' on Juejin."), AgentBrain(evaluation_previous_goal="Success - Successfully searched for the keyword 'AI'.", memory="Task in progress. Searched for 'AI' (3/3 keywords completed). Next, extract the top 5 articles for 'AI'.", next_goal="Extract the top 5 articles for 'AI'."), AgentBrain(evaluation_previous_goal="Success - Extracted the top 5 articles for 'AI'.", memory="Task completed. Searched for all 3 keywords ('Vue', 'React', 'AI') and extracted the top 5 articles for each. Total of 15 articles collected.", next_goal='Compile and return the final results.')] history.action_results()---> [ActionResult(is_done=False, success=None, extracted_content='🔗  Navigated to https://juejin.cn', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='⌨️  Input Vue into index 11', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='🖱️  Clicked button with index 11: ', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='📄  Extracted from pagen: ```jsonn{n  "top_5_vue_articles": [n    {n      "post_title": "vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板",n      "post_url": "https://juejin.cn/post/7486369696738017321"n    },n    {n      "post_title": "🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!",n      "post_url": "https://juejin.cn/post/7484131071569772595"n    },n    {n      "post_title": "前端佬们!塌房了!用过Element-Plus的进来~",n      "post_url": "https://juejin.cn/post/7485966905418760227"n    },n    {n      "post_title": "和后端大战三百回合后,卑微前端还是选择了自己写excel导出",n      "post_url": "https://juejin.cn/post/7447368539936587776"n    },n    {n      "post_title": "从 DeepSeek 看25年前端的一个小趋势",n      "post_url": "https://juejin.cn/post/7468323178931879972"n    }n  ]n}n```n', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='⌨️  Input React into index 11', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='🖱️  Clicked button with index 11: ', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='📄  Extracted from pagen: ```jsonn{n  "top_5_react_articles": [n    {n      "post_title": "🚀🚀🚀尤雨溪连发两条推特墙裂推荐的这些库你一定要知道!",n      "post_url": "/post/7484131071569772595"n    },n    {n      "post_title": "前端佬们!塌房了!用过Element-Plus的进来~",n      "post_url": "/post/7485966905418760227"n    },n    {n      "post_title": "和后端大战三百回合后,卑微前端还是选择了自己写excel导出",n      "post_url": "/post/7447368539936587776"n    },n    {n      "post_title": "vue3.5+deepseek+arco+markdown搭建web版流式输出AI模板",n      "post_url": "/post/7486369696738017321"n    },n    {n      "post_title": "从 DeepSeek 看25年前端的一个小趋势",n      "post_url": "/post/7468323178931879972"n    }n  ]n}n```n', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='⌨️  Input AI into index 11', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='🖱️  Clicked button with index 11: ', error=None, include_in_memory=True), ActionResult(is_done=False, success=None, extracted_content='📄  Extracted from pagen: ```jsonn{n  "top_5_ai_articles": [n    {n      "post_title": "有了Trae,人人都是程序员的时代来了",n      "post_url": "/post/7463397212120973375"n    },n    {n      "post_title": "正式宣战,DeepSeek 顶得住吗?",n      "post_url": "/post/7464848482987704329"n    },n    {n      "post_title": "用 DeepSeek 打造你的超强代码助手",n      "post_url": "/post/7454888708588945443"n    },n    {n      "post_title": "刚刚,DeepSeek 解答了困扰我五年的技术问题。时代确实变了!",n      "post_url": "/post/7472248441454018575"n    },n    {n      "post_title": "放弃没用的本地部署残血版DeepSeek吧,教你如何白嫖满血版DeepSeek",n      "post_url": "/post/7466832084486914083"n    }n  ]n}n```n', error=None, include_in_memory=True), ActionResult(is_done=True, success=True, extracted_content='{"posts": [{"post_title": "vue3.5+deepseek+arco+markdown\u642d\u5efaweb\u7248\u6d41\u5f0f\u8f93\u51faAI\u6a21\u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "\ud83d\ude80\ud83d\ude80\ud83d\ude80\u5c24\u96e8\u6eaa\u8fde\u53d1\u4e24\u6761\u63a8\u7279\u5899\u88c2\u63a8\u8350\u7684\u8fd9\u4e9b\u5e93\u4f60\u4e00\u5b9a\u8981\u77e5\u9053\uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "\u524d\u7aef\u4f6c\u4eec\uff01\u584c\u623f\u4e86\uff01\u7528\u8fc7Element-Plus\u7684\u8fdb\u6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "\u548c\u540e\u7aef\u5927\u6218\u4e09\u767e\u56de\u5408\u540e\uff0c\u5351\u5fae\u524d\u7aef\u8fd8\u662f\u9009\u62e9\u4e86\u81ea\u5df1\u5199excel\u5bfc\u51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "\u4ece DeepSeek \u770b25\u5e74\u524d\u7aef\u7684\u4e00\u4e2a\u5c0f\u8d8b\u52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "\ud83d\ude80\ud83d\ude80\ud83d\ude80\u5c24\u96e8\u6eaa\u8fde\u53d1\u4e24\u6761\u63a8\u7279\u5899\u88c2\u63a8\u8350\u7684\u8fd9\u4e9b\u5e93\u4f60\u4e00\u5b9a\u8981\u77e5\u9053\uff01", "post_url": "https://juejin.cn/post/7484131071569772595"}, {"post_title": "\u524d\u7aef\u4f6c\u4eec\uff01\u584c\u623f\u4e86\uff01\u7528\u8fc7Element-Plus\u7684\u8fdb\u6765~", "post_url": "https://juejin.cn/post/7485966905418760227"}, {"post_title": "\u548c\u540e\u7aef\u5927\u6218\u4e09\u767e\u56de\u5408\u540e\uff0c\u5351\u5fae\u524d\u7aef\u8fd8\u662f\u9009\u62e9\u4e86\u81ea\u5df1\u5199excel\u5bfc\u51fa", "post_url": "https://juejin.cn/post/7447368539936587776"}, {"post_title": "vue3.5+deepseek+arco+markdown\u642d\u5efaweb\u7248\u6d41\u5f0f\u8f93\u51faAI\u6a21\u677f", "post_url": "https://juejin.cn/post/7486369696738017321"}, {"post_title": "\u4ece DeepSeek \u770b25\u5e74\u524d\u7aef\u7684\u4e00\u4e2a\u5c0f\u8d8b\u52bf", "post_url": "https://juejin.cn/post/7468323178931879972"}, {"post_title": "\u6709\u4e86Trae\uff0c\u4eba\u4eba\u90fd\u662f\u7a0b\u5e8f\u5458\u7684\u65f6\u4ee3\u6765\u4e86", "post_url": "https://juejin.cn/post/7463397212120973375"}, {"post_title": "\u6b63\u5f0f\u5ba3\u6218\uff0cDeepSeek \u9876\u5f97\u4f4f\u5417\uff1f", "post_url": "https://juejin.cn/post/7464848482987704329"}, {"post_title": "\u7528 DeepSeek \u6253\u9020\u4f60\u7684\u8d85\u5f3a\u4ee3\u7801\u52a9\u624b", "post_url": "https://juejin.cn/post/7454888708588945443"}, {"post_title": "\u521a\u521a\uff0cDeepSeek \u89e3\u7b54\u4e86\u56f0\u6270\u6211\u4e94\u5e74\u7684\u6280\u672f\u95ee\u9898\u3002\u65f6\u4ee3\u786e\u5b9e\u53d8\u4e86\uff01", "post_url": "https://juejin.cn/post/7472248441454018575"}, {"post_title": "\u653e\u5f03\u6ca1\u7528\u7684\u672c\u5730\u90e8\u7f72\u6b8b\u8840\u7248DeepSeek\u5427\uff0c\u6559\u4f60\u5982\u4f55\u767d\u5ad6\u6ee1\u8840\u7248DeepSeek", "post_url": "https://juejin.cn/post/7466832084486914083"}]}', error=None, include_in_memory=False)] 

4. Prompt

用于 控制 Agent 的行为与能力,对其整体逻辑有深层影响。

自定义提示会显著影响性能、稳定性和输出风格。

message_context 字段

5. 持久化会话

增加 Cookie

context_config = BrowserContextConfig(cookies_file="cookies.json") 

五、Demo 示例

1. 简单示例

#!/usr/bin/env python3 # -*- coding: utf-8 -*-  import asyncio from dotenv import load_dotenv from langchain_openai import ChatOpenAI from browser_use import Agent  load_dotenv()  llm = ChatOpenAI(model="gpt-4o")  async def main():     agent = Agent(         task="打开 https://cn.vuejs.org/guide/essentials/computed,获取页面里所有的 h2 标签文本及所有的 a 标签文本(以及它的 href)",         llm=llm,     )     result = await agent.run()     print('result:',result)  if __name__ == "__main__":     asyncio.run(main()) 

1.1. 核心流程:

  1. 从 .env 中读取 OPENAI_API_KEY 等信息,初始化 ChatOpenAI。
  2. 创建一个 Agent,指定 task 即描述智能体要完成的任务。
  3. 调用 agent.run() 发起执行,包括浏览器自动化与 LLM 结合的流程。

2. 使用本地的 Chrome 浏览器

#!/usr/bin/env python3 # -*- coding: utf-8 -*-  from browser_use import Agent, Browser, BrowserConfig from langchain_openai import ChatOpenAI from dotenv import load_dotenv import asyncio  load_dotenv() browser = Browser(     config=BrowserConfig(         chrome_instance_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',     ) )  llm = ChatOpenAI(model="gpt-4o")  agent = Agent(     task="打开 https://cn.vuejs.org/guide/essentials/computed,获取页面里所有的 h2 标签文本及所有的 a 标签文本(以及它的 href)",     llm=llm,     browser=browser, )  async def main():     await agent.run()     await browser.close()  if __name__ == '__main__':     asyncio.run(main()) 

3. Prompt

from pydantic import BaseModel from typing import List from dotenv import load_dotenv from browser_use import Agent, Controller, Browser, BrowserConfig from langchain_openai import ChatOpenAI import asyncio  class WikiResult(BaseModel):     post_title: str     post_url: str  class WikiResults(BaseModel):     posts: List[WikiResult]   load_dotenv()  browser = Browser(     config=BrowserConfig(         chrome_instance_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',     ) )  instruction_message = """ 你正在访问一个公司内部 Wiki 系统:http://wiki.xxx.com/pages/  你的目标是: 1. 打开该页面并使用搜索功能,输入关键词:RAP 2. 等待页面加载完毕,提取所有与搜索结果相关的条目,包括标题、简要描述和对应链接。 3. 优先提取条目中出现 "接口管理"、"Mock"、"权限" 等关键词的内容。 4. 将所有结果以列表形式返回。  请确保你的返回格式如下: {   "posts": [     {       "post_title": "xxx",       "post_url": "http://..."     },     ...   ] } """  controller = Controller(output_model=WikiResults)  async def main():     task = "搜索 Wiki 中有关 RAP 的内容"     model = ChatOpenAI(model='gpt-4o')      agent = Agent(         task=task,         llm=model,         controller=controller,         browser=browser,         message_context=instruction_message     )      history = await agent.run()     result = history.final_result()      if result:         parsed: WikiResults = WikiResults.model_validate_json(result)          for post in parsed.posts:             print('n--------------------------------')             print(f'Title:  {post.post_title}')             print(f'URL:    {post.post_url}')     else:         print('No result')   if __name__ == '__main__':     asyncio.run(main()) 

4. 多个 Agent 执行

agent1 = Agent(     task="打开 https://cn.vuejs.org/guide/essentials/computed,获取页面里所有的 h2 标签文本及所有的 a 标签文本(以及它的 href)",     llm=llm,     use_vision=False ) result1 = await agent1.run() agent2 = Agent(     task="打开 https://docs.browser-use.com/customize/custom-functions,获取页面里所有的 h2 标签文本及所有的 a 标签文本(以及它的 href)",     llm=llm,     use_vision=False ) result2 = await agent2.run() 

六、常见操作

1. 修改 LLM 模型

llm = ChatOpenAI(model="gpt-3.5-turbo") 

llm = ChatOpenAI(model="gpt-4o") 

2. 在 .env 中设置 API Key

OPENAI_API_KEY=sk-xxxx ANTHROPIC_API_KEY=xxxxxx 

如果你还需使用其他模型(如 Cohere、HuggingFace Hub),可一并配置对应的 Key,并在 Python 脚本中初始化相应的 LLM 对象。

3. 官方文档示例

docs.browser-use.com/introduction 可以找到更多场景示例,比如如何定制 browser-use 的 Tools、配合 PythonREPLTool 扩展执行 Python 脚本等。


七、UI 测试方式

1. 安装 Gradio

pip3 install gradio 

2. 运行示例

import asyncio  import gradio as gr from dotenv import load_dotenv from langchain_openai import ChatOpenAI  from browser_use import Agent  load_dotenv()   llm=ChatOpenAI(base_url='https://api.deepseek.com/v1', model='deepseek-chat', api_key="sk-XXX")  async def run_browser_task(     task: str, ) -> str:     try:         print('task', task)         agent = Agent(             task=task,             llm=llm,             use_vision=False         )         result = await agent.run()         print('final_result()', result.final_result())         return result     except Exception as e:         return f'Error: {str(e)}'   def create_ui():     with gr.Blocks(title='Browser Use GUI') as interface:         gr.Markdown('# Browser Use Task Automation')          with gr.Row():             with gr.Column():                 task = gr.Textbox(                     label='Task Description',                     placeholder='Task 描述',                     lines=3,                 )                 model = gr.Dropdown(                     choices=['gpt-4', 'gpt-3.5-turbo'], label='Model', value='gpt-4'                 )                 headless = gr.Checkbox(label='Run Headless', value=True)                 submit_btn = gr.Button('Run Task')              with gr.Column():                 output = gr.Textbox(label='Output', lines=10, interactive=False)          submit_btn.click(             fn=lambda *args: asyncio.run(run_browser_task(task.value)),             inputs=[task, model, headless],             outputs=output,         )      return interface   if __name__ == '__main__':     demo = create_ui()     demo.launch() 

打开终端提示的地址,就能看到一个简易的 web 界面,在界面中输入 task 等信息测试智能体。

Browser-use:基于 Python 的智能浏览器自动化 AI 工具调研与实战


八、常见问题 & 解决思路

  • 报错:playwright not installed 或 executable path not found
    • 请确认已执行 playwright install chromium,且安装成功。
  • Python 版本过低
    • Browser-use 要求 Python >= 3.11,如果你使用的是 3.10 或更低版本,需要升级环境。
  • LLM 调用失败
    • 检查是否在 .env 中填写了正确的 API key,或你的 Key 是否仍在有效期内。
  • 一直执行 Step1
    • Key 没钱了...
  • UI Demo 启动后无法访问
    • 可能是端口占用,或者 Gradio 版本过旧。尝试更新 gradio 或换一个端口。
  • 长时间卡住/超时
    • 检查网络环境,LLM 请求或浏览器加载是否耗时过长。
  • DeepSeek
    • 需要添加 use_vision=False 字段

九、总结

Browser-use 让 AI 与浏览器的结合变得更便捷,能够快速构建出“会浏览网页、抓取信息、进行动态交互”的智能体。只需简单的配置与几行代码,就能让 LLM 自动处理网页操作,为项目带来更多可能性。

  • 使用 Python >= 3.11;
  • 安装并配置好 Playwright;
  • 在主代码中初始化 Agent 并提供 LLM;
  • 在 .env 中存放 API Keys;

十、参考

发表评论

您必须 [ 登录 ] 才能发表留言!

相关文章