Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Add export_storage_state method to BrowserSession for cookie and storage export
Magnus Müller5601401c1167
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex fcba83fc9..c0f942aba 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -986,6 +986,51 @@ class BrowserSession(BaseModel):"""Clear all cookies."""await self.cdp_client.send.Network.clearBrowserCookies()+ async def export_storage_state(self, output_path: str | Path | None = None) -> dict[str, Any]:+ """Export all browser cookies and storage to storage_state format.++ Extracts decrypted cookies via CDP, bypassing keychain encryption.++ Args:+ output_path: Optional path to save storage_state.json. If None, returns dict only.++ Returns:+ Storage state dict with cookies in Playwright format.++ """+ from pathlib import Path++ # Get all cookies using Storage.getCookies (returns decrypted cookies from all domains)+ cookies = await self._cdp_get_cookies()++ # Convert CDP cookie format to Playwright storage_state format+ storage_state = {+ 'cookies': [+ {+ 'name': c['name'],+ 'value': c['value'],+ 'domain': c['domain'],+ 'path': c['path'],+ 'expires': c.get('expires', -1),+ 'httpOnly': c.get('httpOnly', False),+ 'secure': c.get('secure', False),+ 'sameSite': c.get('sameSite', 'Lax'),+ }+ for c in cookies+ ],+ 'origins': [], # Could add localStorage/sessionStorage extraction if needed+ }++ if output_path:+ import json++ output_file = Path(output_path).expanduser().resolve()+ output_file.parent.mkdir(parents=True, exist_ok=True)+ output_file.write_text(json.dumps(storage_state, indent=2))+ self.logger.info(f'💾 Exported {len(cookies)} cookies to {output_file}')++ return storage_state+async def get_or_create_cdp_session(self, target_id: TargetID | None = None, focus: bool = True, new_socket: bool | None = None) -> CDPSession:diff --git a/examples/browser/real_browser.py b/examples/browser/real_browser.pyindex f56e811d1..a01f14755 100644--- a/examples/browser/real_browser.py+++ b/examples/browser/real_browser.py@@ -19,6 +19,7 @@ browser = Browser(async def main():+ # save storage stateagent = Agent(llm=ChatGoogle(model='gemini-flash-latest'),# Google blocks this approach, so we use a different search enginediff --git a/examples/browser/save_cookies.py b/examples/browser/save_cookies.pynew file mode 100644index 000000000..eef6565f5--- /dev/null+++ b/examples/browser/save_cookies.py@@ -0,0 +1,27 @@+import asyncio+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from dotenv import load_dotenv++load_dotenv()++from browser_use import Browser++# Connect to your existing Chrome browser+browser = Browser(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ user_data_dir='~/Library/Application Support/Google/Chrome',+ profile_directory='Default',+)+++async def main():+ await browser.start()+ await browser.export_storage_state('storage_state3.json')+++if __name__ == '__main__':+ asyncio.run(main())