用 selenium 打开多个 chrome 配置文件

open multiple chrome profile with selenium

当我 运行 此代码 chrome 已经打开时,我收到此错误: 消息:参数无效:用户数据目录已在使用中,请为 --user-data-dir 参数指定一个唯一值,或者不要使用 --user-data-dir

我需要同时打开多个配置文件,我该怎么办?

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("user-data-dir=C:\Users\utent\AppData\Local\Google\Chrome\User Data")
options.add_argument("--profile-directory=Profile 3")
driver = webdriver.Chrome(executable_path=r'C:\Development\chromedriver.exe', options=options)

driver.get("https://www.instagram.com")

假设您要打开两个 chrome 个配置文件

您需要使用要设置的配置文件实例化两个 Web 驱动程序。

从实例化我的意思是,您需要创建两个 chrome 网络驱动程序,因为一旦设置了选项并且您已经创建了 驱动程序 ,您以后就无法更改它

所以,

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = [Options(), Options()]
options[0].add_argument("user-data-dir=C:\Users\utent\AppData\Local\Google\Chrome\User Data")
options[1].add_argument("user-data-dir=C:\Users\utent\AppData\Local\Google\Chrome\User Data")

options[0].add_argument("--profile-directory=Profile 3")
options[1].add_argument("--profile-directory=Profile 4") # add another profile path

drivers = [webdriver.Chrome(executable_path=r'C:\Development\chromedriver.exe', options=options[0]), webdriver.Chrome(executable_path=r'C:\Development\chromedriver.exe', options=options[1])]

drivers[0].get("https://instagram.com")
drivers[1].get("https://instagram.com")

用户数据目录被第一个实例锁定,第二个实例异常失败 所以解决方案是为每个配置文件创建一个用户数据

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--user-data-dir=C:\anyPathWhereYouWantToSaveYourUserData\profile1")
driver = webdriver.Chrome(executable_path=r'C:\Windows\System32\chromedriver.exe', options=options)
driver.get("https://www.instagram.com")

不用担心,如果您只想创建快捷方式,您现在可以手动访问您的新配置文件,只需将其添加到您的快捷方式中的目标即可

"C:\Program Files\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\anyPathWhereYouWantToSaveYourUserData\profile1"