Browser-use の Version 0.2.5 で、永続的にブラウザーを使い続ける方法を探し、動作確認しました。
課題の背景
Version 0.2.5 では、ブラウザのセッション管理は基本的にエージェントが勝手に行うようになり、Close を入れなくても勝手に閉じてしまいます。
対話式で使いたいのに、これは困った・・・。
そこで、調査しました。
コード
動作するコードは以下のものです。
import asyncio
import os
from browser_use import BrowserSession, Agent, SystemPrompt
from langchain_google_genai import ChatGoogleGenerativeAI
from dotenv import load_dotenv
load_dotenv()
extend_system_message = """
REMEMBER the most important RULE:
- Please do not follow links unless necessary, no matter the task!!!
"""
async def process_command(query: str, page, llm) -> None:
"""単一のコマンドを処理する関数"""
try:
agent = Agent(
task=query,
llm=llm,
page=page, # 同じページオブジェクトを再利用
extend_system_message=extend_system_message
)
result = await agent.run(max_steps=5)
print(f"✅ 結果: {result}")
except Exception as e:
print(f"❌ コマンド処理エラー: {e}")
async def main():
# APIキーの設定
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
print("❌ APIキーが設定されていません")
return
# LLMを初期化
llm = ChatGoogleGenerativeAI(
# model="gemini-2.5-flash-preview-05-20",
model="gemini-2.0-flash-exp",
google_api_key=api_key,
)
# ブラウザセッションを作成
browser_session = BrowserSession(
headless=False,
user_data_dir='~/.config/browseruse/profiles/interactive_session',
disable_security=True,
)
try:
print("🚀 ブラウザセッションを開始しています...")
await browser_session.start()
# ページオブジェクトを取得
page = await browser_session.get_current_page()
print("✅ ブラウザセッションが開始されました!")
print("💡 ヒント: 'quit' または 'exit' で終了します")
print("=" * 60)
# 対話式ループ
while True:
try:
query = input("\n🔍 コマンドを入力してください: ").strip()
# 終了コマンドをチェック
if query.lower() in ['quit', 'exit', 'q']:
print("👋 セッションを終了します...")
break
# 空の入力をスキップ
if not query:
print("⚠️ コマンドを入力してください")
continue
# ヘルプコマンド
if query.lower() in ['help', 'h']:
print("""
📖 使用可能なコマンド例:
• Goto https://example.com/ - ウェブサイトに移動
• ページのタイトルを確認してください - ページ情報を取得
• 検索ボックスに'Python'と入力してください - フォーム操作
• ページ上のリンクを確認してください - リンク一覧表示
• スクリーンショットを撮ってください - 画面キャプチャ
• quit / exit - 終了
• help / h - このヘルプ
""")
continue
print(f"⚡ 実行中: {query}")
await process_command(query, page, llm)
except KeyboardInterrupt:
print("\n⚠️ Ctrl+Cが押されました。終了しますか? (y/N): ", end="")
response = input().strip().lower()
if response in ['y', 'yes']:
break
except Exception as e:
print(f"❌ 予期しないエラー: {e}")
continue
except Exception as e:
print(f"❌ ブラウザセッション開始エラー: {e}")
finally:
try:
await browser_session.close()
print("✅ ブラウザセッションを正常に終了しました")
except Exception as e:
print(f"⚠️ ブラウザセッション終了時にエラー: {e}")
if __name__ == "__main__":
print("🌐 Browser-Use 対話式セッション")
print("=" * 60)
asyncio.run(main())
要点
user_data_dir
が、ちょっとしたカギです。