Wie lade und verwende ich eine Erweiterung innerhalb der Browser-Nutzung?Python

Python-Programme
Guest
 Wie lade und verwende ich eine Erweiterung innerhalb der Browser-Nutzung?

Post by Guest »

Ich verwende Browser-Nutzung für die Webautomatisierung. Dieses Paket nutzt Dramatiker unter der Haube. Mir ist aufgefallen, dass es nicht möglich ist, eine Erweiterung im Inkognito-Modus zu laden, daher muss ich playwright.chromium.launch_persistent_context anstelle von playwright.chromium.launch verwenden. Bei der Browsernutzung wird jedoch playwright.chromium.launch verwendet. Deshalb wollte ich die Browser-Klasse überschreiben, um dies zu ändern und meine Erweiterung dort zu laden. Allerdings bleibt der folgende Code, den ich bisher geschrieben habe, hängen und die Chromium-Instanz wird nicht wie im normalen Modus ausgeführt:

Code: Select all

import asyncio
import os

from browser_use import Agent, BrowserConfig, Browser
from browser_use.browser.browser import logger
from langchain_openai import ChatOpenAI
from playwright.async_api import async_playwright, Playwright

extension_path = "/home/benyamin/PycharmProjects/stack/capsolver-extension

class CustomBrowser(Browser):
async def _setup_browser(self, playwright: Playwright):
"""Sets up and returns a Playwright Browser instance with persistent context."""
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
subprocess.Popen(
[
self.config.chrome_instance_path,
'--remote-debugging-port=9222',
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)

# Attempt to connect again after starting a new instance
try:
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:
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',
]

# Use launch_persistent_context instead of launch
user_data_dir = os.path.join(os.getcwd(), "user_data") # Specify the path to the user data directory
browser_context = await playwright.chromium.launch_persistent_context(
user_data_dir=user_data_dir,
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',
# f"--disable-extensions-except={extension_path}",
# f'--load-extension={extension_path}',  # Load the extension
]
+ disable_security_args
+ self.config.extra_chromium_args,
proxy=self.config.proxy,
)

return browser_context
except Exception as e:
logger.error(f'Failed to initialize Playwright browser: {str(e)}')
raise

config = BrowserConfig(
extra_chromium_args=[
f"--disable-extensions-except={extension_path}",
f"--load-extension={extension_path}",
"--disable-web-security",  # Optional, for testing purposes
"--disable-site-isolation-trials"
]
)
browser = CustomBrowser(config=config)

async def main():
# custom_browser = CustomBrowser(config=BrowserConfig())
agent = Agent(
task="Go to Reddit, search for 'browser-use' in the search bar, click on the first post and return the first comment.",
llm=ChatOpenAI(model="gpt-4o"),
browser=browser,
)
result = await agent.run()
print(result)

asyncio.run(main())

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post