Как загрузить и использовать расширение в браузере?Python

Программы на Python
Ответить
Anonymous
 Как загрузить и использовать расширение в браузере?

Сообщение Anonymous »

Я использую браузер для веб-автоматизации. Этот пакет использует драматурга под капотом. Я понял, что невозможно загрузить расширение в режиме инкогнито, поэтому мне пришлось использовать playwright.chromium.launch_persistent_context вместо playwright.chromium.launch. Но при использовании браузера используется playwright.chromium.launch. Поэтому я хотел переопределить класс Browser, чтобы изменить это и загрузить туда свое расширение. Однако следующий код, который я написал, зависает, и экземпляр Chromium не запускается в обычном режиме:
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 = "/path/to/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())


Подробнее здесь: https://stackoverflow.com/questions/793 ... rowser-use
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»