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
Updated lint changes
avocardiobb01a5e96156
diff --git a/docs/examples/apps/msg-use.mdx b/docs/examples/apps/msg-use.mdxindex 137dc0682..e6aa9c26a 100644--- a/docs/examples/apps/msg-use.mdx+++ b/docs/examples/apps/msg-use.mdx@@ -142,4 +142,4 @@ asyncio.run(advanced_scheduling())## Source Code-Full implementation: [https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use](https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use)\ No newline at end of file+Full implementation: [https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use](https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use)diff --git a/examples/apps/msg-use/login.py b/examples/apps/msg-use/login.pyindex 09be44c32..a5cf40cbd 100644--- a/examples/apps/msg-use/login.py+++ b/examples/apps/msg-use/login.py@@ -14,27 +14,24 @@ USER_DATA_DIR.mkdir(parents=True, exist_ok=True)# Storage state file for cookiesSTORAGE_STATE_FILE = USER_DATA_DIR / 'storage_state.json'+async def login_to_whatsapp():- """Open WhatsApp Web and wait for user to scan QR code"""- if not GOOGLE_API_KEY:- print("❌ Error: GOOGLE_API_KEY environment variable is required")- print("Please set it with: export GOOGLE_API_KEY='your-api-key-here'")- return-- print("WhatsApp Login Setup")- print("=" * 50)- print(f"Browser profile directory: {USER_DATA_DIR}")- print(f"Storage state file: {STORAGE_STATE_FILE}")- print("=" * 50)-- try:- llm = ChatGoogle(- model="gemini-2.0-flash-exp",- temperature=0.3,- api_key=GOOGLE_API_KEY- )-- task = """+ """Open WhatsApp Web and wait for user to scan QR code"""+ if not GOOGLE_API_KEY:+ print('❌ Error: GOOGLE_API_KEY environment variable is required')+ print("Please set it with: export GOOGLE_API_KEY='your-api-key-here'")+ return++ print('WhatsApp Login Setup')+ print('=' * 50)+ print(f'Browser profile directory: {USER_DATA_DIR}')+ print(f'Storage state file: {STORAGE_STATE_FILE}')+ print('=' * 50)++ try:+ llm = ChatGoogle(model='gemini-2.0-flash-exp', temperature=0.3, api_key=GOOGLE_API_KEY)++ task = """You are helping a user log into WhatsApp Web. Follow these steps:1. Navigate to https://web.whatsapp.com@@ -45,33 +42,30 @@ async def login_to_whatsapp():Take your time and be patient with page loads."""-- print("\nOpening WhatsApp Web...")- print("Please scan the QR code when it appears.\n")-- browser_session = BrowserSession(- headless=False, # Show browser- user_data_dir=str(USER_DATA_DIR), # Use persistent profile directory- storage_state=str(STORAGE_STATE_FILE) if STORAGE_STATE_FILE.exists() else None # Use saved cookies/session- )-- agent = Agent(- task=task,- llm=llm,- browser_session=browser_session- )-- result = await agent.run()-- print("\n✅ Login completed!")- print("Note: For now, you'll need to scan the QR code each time.")- print("We'll improve session persistence in a future update.")- print("\nPress Enter to close the browser...")- input()-- except Exception as e:- print(f"\n❌ Error during login: {str(e)}")- print("Please try again.")-if __name__ == "__main__":- asyncio.run(login_to_whatsapp())\ No newline at end of file+ print('\nOpening WhatsApp Web...')+ print('Please scan the QR code when it appears.\n')++ browser_session = BrowserSession(+ headless=False, # Show browser+ user_data_dir=str(USER_DATA_DIR), # Use persistent profile directory+ storage_state=str(STORAGE_STATE_FILE) if STORAGE_STATE_FILE.exists() else None, # Use saved cookies/session+ )++ agent = Agent(task=task, llm=llm, browser_session=browser_session)++ result = await agent.run()++ print('\n✅ Login completed!')+ print("Note: For now, you'll need to scan the QR code each time.")+ print("We'll improve session persistence in a future update.")+ print('\nPress Enter to close the browser...')+ input()++ except Exception as e:+ print(f'\n❌ Error during login: {str(e)}')+ print('Please try again.')+++if __name__ == '__main__':+ asyncio.run(login_to_whatsapp())diff --git a/examples/apps/msg-use/scheduler.py b/examples/apps/msg-use/scheduler.pyold mode 100644new mode 100755index a3495c480..4c2335cde--- a/examples/apps/msg-use/scheduler.py+++ b/examples/apps/msg-use/scheduler.py@@ -2,6 +2,7 @@"""WhatsApp Message Scheduler - Send scheduled messages via WhatsApp Web"""+import argparseimport asyncioimport json@@ -42,18 +43,16 @@ async def parse_messages():"""Parse messages.txt and extract scheduling info"""messages_file = Path('messages.txt')if not messages_file.exists():- print("❌ messages.txt not found!")+ print('❌ messages.txt not found!')return []-- with open(messages_file, 'r') as f:- content = f.read()-- llm = ChatGoogle(- model='gemini-2.0-flash-exp',- temperature=0.1,- api_key=GOOGLE_API_KEY- )-++ import aiofiles++ async with aiofiles.open(messages_file) as f:+ content = await f.read()++ llm = ChatGoogle(model='gemini-2.0-flash-exp', temperature=0.1, api_key=GOOGLE_API_KEY)+now = datetime.now()prompt = f"""Parse these WhatsApp message instructions and extract:@@ -93,11 +92,12 @@ async def parse_messages():- "tomorrow" means {(now + timedelta(days=1)).strftime('%Y-%m-%d')}- "next tuesday" or similar means the next occurrence of that day"""-+from browser_use.llm.messages import UserMessage+response = await llm.ainvoke([UserMessage(content=prompt)])response_text = response.completion if hasattr(response, 'completion') else str(response)-+# Extract JSONjson_match = re.search(r'\[.*?\]', response_text, re.DOTALL)if json_match:@@ -108,21 +108,17 @@ async def parse_messages():msg['message'] = re.sub(r'\n+', ' • ', msg['message'])msg['message'] = re.sub(r'\s+', ' ', msg['message']).strip()return messages- except:+ except json.JSONDecodeError:passreturn []async def send_message(contact, message):"""Send a WhatsApp message"""- print(f"\n📱 Sending to {contact}: {message}")-- llm = ChatGoogle(- model='gemini-2.0-flash-exp',- temperature=0.3,- api_key=GOOGLE_API_KEY- )-+ print(f'\n📱 Sending to {contact}: {message}')++ llm = ChatGoogle(model='gemini-2.0-flash-exp', temperature=0.3, api_key=GOOGLE_API_KEY)+task = f"""Send WhatsApp message:1. Go to https://web.whatsapp.com@@ -132,104 +128,104 @@ async def send_message(contact, message):5. Press Enter to send6. Confirm sent"""-+browser = BrowserSession(headless=not args.debug, # headless=False only when debug=Trueuser_data_dir=str(USER_DATA_DIR),- storage_state=str(STORAGE_STATE_FILE) if STORAGE_STATE_FILE.exists() else None+ storage_state=str(STORAGE_STATE_FILE) if STORAGE_STATE_FILE.exists() else None,)-+agent = Agent(task=task, llm=llm, browser_session=browser)await agent.run()- print(f"✅ Sent to {contact}")+ print(f'✅ Sent to {contact}')async def main():if not GOOGLE_API_KEY:- print("❌ Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable")+ print('❌ Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable')return-- print("WhatsApp Scheduler")- print(f"Profile: {USER_DATA_DIR}")++ print('WhatsApp Scheduler')+ print(f'Profile: {USER_DATA_DIR}')print()-+# Parse messages- print("Parsing messages.txt...")+ print('Parsing messages.txt...')messages = await parse_messages()-+if not messages:- print("No messages found")+ print('No messages found')return-- print(f"\nFound {len(messages)} messages:")++ print(f'\nFound {len(messages)} messages:')for msg in messages:- print(f" • {msg['datetime']}: {msg['message'][:30]}... to {msg['contact']}")-+ print(f' • {msg["datetime"]}: {msg["message"][:30]}... to {msg["contact"]}')+now = datetime.now()immediate = []future = []-+for msg in messages:msg_time = datetime.strptime(msg['datetime'], '%Y-%m-%d %H:%M')if msg_time <= now:immediate.append(msg)else:future.append(msg)-+if args.test:- print(f"\n=== TEST MODE - Preview ===")+ print('\n=== TEST MODE - Preview ===')if immediate:- print(f"\nWould send {len(immediate)} past-due messages NOW:")+ print(f'\nWould send {len(immediate)} past-due messages NOW:')for msg in immediate:- print(f" 📱 To {msg['contact']}: {msg['message']}")+ print(f' 📱 To {msg["contact"]}: {msg["message"]}')if future:- print(f"\nWould monitor {len(future)} future messages:")+ print(f'\nWould monitor {len(future)} future messages:')for msg in future:- print(f" ⏰ {msg['datetime']}: To {msg['contact']}: {msg['message']}")- print("\nTest mode complete. No messages sent.")+ print(f' ⏰ {msg["datetime"]}: To {msg["contact"]}: {msg["message"]}')+ print('\nTest mode complete. No messages sent.')return-+if immediate:- print(f"\nSending {len(immediate)} past-due messages NOW...")+ print(f'\nSending {len(immediate)} past-due messages NOW...')for msg in immediate:await send_message(msg['contact'], msg['message'])-+if future:- print(f"\n⏰ Monitoring {len(future)} future messages...")- print("Press Ctrl+C to stop.\n")-+ print(f'\n⏰ Monitoring {len(future)} future messages...')+ print('Press Ctrl+C to stop.\n')+last_status = None-+while future:now = datetime.now()due = []remaining = []-+for msg in future:msg_time = datetime.strptime(msg['datetime'], '%Y-%m-%d %H:%M')if msg_time <= now:due.append(msg)else:remaining.append(msg)-+for msg in due:- print(f"\n⏰ Time reached for {msg['contact']}")+ print(f'\n⏰ Time reached for {msg["contact"]}')await send_message(msg['contact'], msg['message'])-+future = remaining-+if future:next_msg = min(future, key=lambda x: datetime.strptime(x['datetime'], '%Y-%m-%d %H:%M'))- current_status = f"Next: {next_msg['datetime']} to {next_msg['contact']}"-+ current_status = f'Next: {next_msg["datetime"]} to {next_msg["contact"]}'+if current_status != last_status:print(current_status)last_status = current_status-+await asyncio.sleep(30) # Check every 30 seconds-- print("\n✅ All messages processed!")++ print('\n✅ All messages processed!')if __name__ == '__main__':- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())