import asyncio
import os
import subprocess
import time
import logging
from playwright._impl._api_structures import ProxySettings
from langchain_openai import AzureChatOpenAI
from browser_use import Agent, Browser, BrowserConfig
from browser_use.browser.context import BrowserContextConfig
from dotenv import load_dotenv
# Load environment variables from the .env file
load_dotenv(r"C:\Users\YINL\OneDrive - Bird & Bird LLP\Desktop\jupyter notebooks\.env")
logger = logging.getLogger(__name__)
llm = AzureChatOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_ID"],
openai_api_version=os.environ["OPENAI_API_VERSION"],
)
# Define the context configuration
context_config = BrowserContextConfig(
browser_window_size={"width": 1280, "height": 720},
disable_security=True,
)
# Configure and initialize the browser
browser = Browser(
config=BrowserConfig(
headless=False,
disable_security=True,
chrome_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
extra_chromium_args=[
r"--user-data-dir=C:\Users\YINL\AppData\Local\Google\Chrome\User Data"
],
new_context_config=context_config,
# wss_url="ws://[Redacted IPAddress]:9222/devtools/browser/9912b374-3b7b-4c0b-8454-5e6a72e12345",
)
)
async def main():
agent = Agent(
task="search 'openai' on google.com and describe the result page.",
llm=llm,
use_vision=True,
browser=browser,
save_conversation_path="logs/conversation.json",
)
result = await agent.run()
print(result)
async def close_existing_chrome_instances():
"""Close existing chrome instances using taskkill for windows."""
try:
subprocess.run(
["taskkill", "/im", "chrome.exe", "/f"],
check=False,
capture_output=True,
)
logger.info("Existing Chrome instances closed.")
except Exception as e:
logger.warning(f"Failed to close existing Chrome instances: {e}")
async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
if self.config.wss_url:
browser = await playwright.chromium.connect(self.config.wss_url)
return browser
elif self.config.chrome_instance_path:
import subprocess
import requests
try:
# Check if browser is already running
response = requests.get('http://localhost:9222/json/version', timeout=2)
if response.status_code == 200:
logger.info('Reusing existing Chrome instance')
browser = await playwright.chromium.connect_over_cdp(
endpoint_url='http://localhost:9222',
timeout=20000, # 20 second timeout for connection
)
return browser
except requests.ConnectionError:
logger.debug('No existing Chrome instance found, starting a new one')
# Start a new Chrome instance
process = subprocess.[Redacted Person](
[
self.config.chrome_instance_path,
'--remote-debugging-port=9222',
],
stdout=subprocess.DEVNULL,
stderr=subprocess.[Redacted Person],
)
# Attempt to connect again after starting a new instance
try:
# Wait for a short time to make sure chrome has time to load
time.sleep(2)
browser = await playwright.chromium.connect_over_cdp(
endpoint_url='http://localhost:9222',
timeout=20000, # 20 second timeout for connection
)
return browser
except Exception as e:
# Check for errors from the subprocess
_, stderr = process.communicate()
if [Redacted Person]:
logger.error(f'Chrome process error: {stderr.decode()}')
logger.error(f'Failed to start a new Chrome instance.: {str(e)}')
raise RuntimeError(
' To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
)
else:
try:
disable_security_args = []
if self.config.disable_security:
disable_security_args = [
'--disable-web-security',
'--disable-site-isolation-trials',
'--disable-features=IsolateOrigins,site-per-process',
]
browser = await playwright.chromium.launch(
headless=self.config.headless,
args=[
'--no-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-infobars',
'--disable-background-timer-throttling',
'--disable-popup-blocking',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-window-activation',
'--disable-focus-on-load',
'--no-first-run',
'--no-default-browser-check',
'--no-startup-window',
'--window-position=0,0',
# '--window-size=1280,1000',
]
+ disable_security_args
+ self.config.extra_chromium_args,
proxy=self.config.proxy,
)
return browser
except Exception as e:
logger.error(f'Failed to initialize Playwright browser: {str(e)}')
raise
if __name__ == "__main__":
asyncio.run(close_existing_chrome_instances())
asyncio.run(main())