Skip to content

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

ability to save trace

Gregor Žunič941122a72c7e
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 72631bc58..f558a0c1c 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -76,6 +76,7 @@ class BrowserContextConfig:
)
save_recording_path: str | None = None
+ trace_path: str | None = None
@dataclass
@@ -118,6 +119,9 @@ class BrowserContext:
await self.save_cookies()
+ if self.config.trace_path:
+ await self.session.context.tracing.stop(path=self.config.trace_path)
+
await self.session.context.close()
def __del__(self):
@@ -197,6 +201,9 @@ class BrowserContext:
record_video_dir=self.config.save_recording_path,
)
+ if self.config.trace_path:
+ await context.tracing.start(screenshots=True, snapshots=True, sources=True)
+
# Load cookies if they exist
if self.config.cookies_file and os.path.exists(self.config.cookies_file):
with open(self.config.cookies_file, 'r') as f:
diff --git a/examples/save_trace.py b/examples/save_trace.py
new file mode 100644
index 000000000..e7b9e4ab9
--- /dev/null
+++ b/examples/save_trace.py
@@ -0,0 +1,32 @@
+import os
+import sys
+
+from langchain_openai import ChatOpenAI
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import asyncio
+
+from browser_use.agent.service import Agent
+from browser_use.browser.browser import Browser
+from browser_use.browser.context import BrowserContextConfig
+
+llm = ChatOpenAI(model='gpt-4o', temperature=0.0)
+
+
+async def main():
+ browser = Browser()
+
+ async with await browser.new_context(
+ config=BrowserContextConfig(trace_path='./tmp/trace.zip')
+ ) as context:
+ agent = Agent(
+ task='Go to hackernews, then go to apple.com and return all titles of open tabs',
+ llm=llm,
+ browser_context=context,
+ )
+ await agent.run()
+
+ await browser.close()
+
+
+asyncio.run(main())