Browser-use:基于 Python 的智能瀏覽器自動化 AI 工具調研與實戰
一、概述
Browser-use 是一個旨在將 AI “智能體”(Agents)與真實瀏覽器進行交互的 Python 庫,可以輕松實現瀏覽器自動化。在配合 LLM(如 GPT 系列)使用時,瀏覽器-use 能夠讓你的智能體發起對網頁的訪問、操作頁面元素、收集信息、執行腳本等,從而擴展 AI 應用的落地場景。
- GitHub: browser-use/browser-use
- 官網: browser-use.com
- 文檔: docs.browser-use.com
目前 Browser-use 最低需要 Python 3.11 及以上,才能正常使用其封裝的 Playwright 功能。
1. 技術棧:
- LangChain(AI Agent框架)
- Playwright(瀏覽器自動化)
- dotenv(環境變量 key)
- 異步I/O架構
2. 流程圖
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 -)"
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 執行流程圖
2. Browser 配置
Browser-use 提供兩個主要配置類:
- BrowserConfig:控制瀏覽器整體行為
- BrowserContextConfig:控制單個上下文(瀏覽器標簽頁/會話)的行為
官方推薦:「1 個 Agent 對應 1 個 Browser 和 1 個 Context」,以增強穩定性和開發體驗。
2.1. BrowserConfig
from browser_use import BrowserConfigconfig = 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 BrowserContextConfigconfig = 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 | {1280, 1100} | 瀏覽器窗口大小,適配大多數 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: strpost_url: strclass 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+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.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 page\n: ```json\n{\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 page\n: ```json\n{\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 page\n: ```json\n{\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 page\n: ```json\n{\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 page\n: ```json\n{\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 page\n: ```json\n{\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 Agentload_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. 核心流程:
- 從 .env 中讀取 OPENAI_API_KEY 等信息,初始化 ChatOpenAI。
- 創建一個 Agent,指定 task 即描述智能體要完成的任務。
- 調用 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 asyncioload_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 asyncioclass WikiResult(BaseModel):post_title: strpost_url: strclass 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 asyncioimport gradio as gr
from dotenv import load_dotenv
from langchain_openai import ChatOpenAIfrom browser_use import Agentload_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 resultexcept 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 interfaceif __name__ == '__main__':demo = create_ui()demo.launch()
打開終端提示的地址,就能看到一個簡易的 web 界面,在界面中輸入 task 等信息測試智能體。
八、常見問題 & 解決思路
- 報錯: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;
十、參考
- GitHub: browser-use/browser-use
- 官網: browser-use.com
- 官方文檔: docs.browser-use.com/introduction