如何使用selenium python同时控制两个google chrome配置文件?

bmvo0sr5  于 2023-03-10  发布在  Go
关注(0)|答案(5)|浏览(399)

我试图控制两个谷歌浏览器示例使用两个不同的配置文件。但当我打开第一个配置文件,然后运行第二个浏览器示例与不同的一个我得到一个错误。

from selenium import webdriver

def launch(login, password):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    chrome_options.add_argument(r'--profile-directory=Profile 3')
    second_options = webdriver.ChromeOptions()
    second_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    second_options.add_argument(r'--profile-directory=Profile 4')
    driver = webdriver.Chrome(options = chrome_options)
    second_driver = webdriver.Chrome(options = second_options)
    driver.get('http://google.com')
    second_driver.get('http://google.com')

if __name__ == '__main__':
    login = 'xxx'
    password = 'xxx'
    launch(login,password)

错误日志:

File "auto.py", line 19, in <module>
    launch(login,password)
  File "auto.py", line 11, in launch_draw
    driver = webdriver.Chrome(options = chrome_options)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  (Driver info: chromedriver=72.0.3626.69 (3c16f8a135abc0d4da2dff33804db79b849a7c38),platform=Linux 4.19.23-1-MANJARO x86_64)

有什么办法让它工作吗?

lyr7nygr

lyr7nygr1#

我相信你可以做到这一点,而不需要网格。尝试添加以下参数到ChromeOptions:

--disable-dev-shm-usage
tcomlyy6

tcomlyy62#

谷歌在下面的文章中指出,如果你同时登录了多个谷歌账户,谷歌可能无法告诉你登录的是哪个账户。我认为解决办法是在登录下一个账户之前先注销一个账户,或者使用一些方法将两个账户的cookie分开。这篇谷歌文章可能会帮助你:
https://support.google.com/accounts/answer/1721977?co=GENIE.Platform%3DDesktop&hl=en

gj3fmq9x

gj3fmq9x3#

Selenium Grid将通过并行运行测试来帮助您进行扩展。只需使用以下命令设置集线器和节点:
对于集线器

java -jar selenium-server-standalone-3.14.0.jar -role hub

并且对于节点

java -jar selenium-server-standalone-3.14.0.jar -role node  -hub http://localhost:4444/grid/register
1cosmwyk

1cosmwyk4#

这可能与您指定配置文件目录的方式有关。
下面的代码对我很有效(似乎与我是否登录没有太大关系)。

  • 假设chrome/user/data中的n〉0个配置文件文件夹保存为“Profile 1”、“Profile 2”、...、“Profilen”

代码

from selenium import webdriver
from selenium.webdriver.chrome.options import DesiredCapabilities
from concurrent.futures import ThreadPoolExecutor
import os, pyautogui, easygui

def new_profile(i):
    global profiles, parent, ev

    profiles[i] = path_profile + str(i)
    o = webdriver.ChromeOptions()
    o.add_argument('--user-data-dir=' + profiles[i])
    d[i] = webdriver.Chrome(path_exec, options=o)
    parent[i] = d[i].current_window_handle
    [ev[i]] = [d[i].execute_script]
    nu = 'x' if i < 10 else 'y'
    try:
        d[i].get('https://' + nu + str(i))
    except:
        pass
    wd[i] = gwwt('x' + i) if i < 10 else gwwt('y' + i)
    d[i].get('google.co.uk')

例如,可以使用以下命令激活第i个浏览器窗口:

wd[i][0].activate()

或者:

wd[i][0].minimize()
wd[i][0].restore

还可以评估jQuery(例如,新选项卡):

ev[i]('open()')

当然,您也可以使用 thread_all() 方法在所有浏览器上异步执行此操作。

def thread_all(ps, fn, parm='', actions=[], workers=6, chunk=1):
    print(f'thread_all({ps}, {fn}, {parm}, {actions}')
    if parm == '':
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, timeout=90, chunksize=max(1, chunk))
    else:
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, itertools.repeat(parm, L), timeout=90, chunksize=max(1, chunk))

def vars_glob():
    global path_profile, path_core, path_exec
    global d, profiles, parent, ev, wd, n, ps
    global gwwt
    resp = easygui.multenterbox('Enter preferences', 'Inputs', ['Number of browsers'],[4])
    try:
        n = int(resp[0])
    except:
        print('enter a digit! run code again please :(')
        quit()
        [gwwt] = [pyautogui.getWindowsWithTitle]
        profiles, d, parent, ev, wd = [''] * n, [''] * n, [''] * n, [''] * n, [['']] * n
        ps = list(range(n))
        path_core = os.path.expanduser("~")
        path_profile = os.path.join(path_core, "AppData", "Local", "Google", "Chrome", "User", "Data", "Profile")
        path_exec = os.path.join(path_core, '< rest of path >', 'chromedriver.exe')

d将是“n”个chrome驱动程序(每个独立浏览器/配置文件一个)

if __name__ == '__main__':
   vars_glob()
   thread_all(ps,new_profile, workers = n+1, chunk = n+1)
0dxa2lsx

0dxa2lsx5#

你不能用同一个selenium webdriver控制两个配置文件。尝试通过一次运行一个配置文件来分开它们。使用undetected_chromedriver时的解决方案。这同样适用于普通的selenium webdriver

import undetected_chromedriver as uc

chrome_profile_path='C:\\Users\\your_name\\AppData\\Local\\Google\\Chrome\\User Data'
    options = uc.ChromeOptions()
    options.add_argument("window-size=1200,700")
    options.add_argument(f"user-data-dir={chrome_profile_path}")
    options.add_argument('profile-directory=Profile 1')
    driver = uc.Chrome(options=options)

相关问题