如何将某些 Chrome 配置文件与 selenium python 一起使用?

How to use certain Chrome profile with selenium python?

距离第一次报道已经过去了6年:https://github.com/SeleniumHQ/selenium/issues/854

从这里 https://chromedriver.chromium.org/getting-started 我试试这个代码:

import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
driver.get('http://www.google.com/');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(60) # Let the user actually see something!
driver.quit()

启动后,转到 chrome://version/ 并查看:

Profile Path C:\Users\USERCU~1\AppData\Local\Temp\scoped_dir13280_930640861\Default

为了设置某些配置文件,我尝试了此处的代码

options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\Users\user123\AppData\Local\Google\Chrome\User Data\Profile 16") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\Users\chromedriver.exe", chrome_options=options)

但是它实际上没有使用指定的路径,而是在另一个配置文件的路径中创建了配置文件,因此 chrome://version 显示:

Profile Path C:\Users\usercuhuh\AppData\Local\Google\Chrome\User Data\Profile 16\Default

所以问题是 \Default 文件夹自动添加到指定的用户数据目录。我怎样才能绕过它并实际启动配置文件 16?

首先


将您的Chrome驱动程序更新到最新版本


(此部分为必填项)。 然后将两个参数 --profile-directory=Profile 1user-data-dir=C:\Users\user123\AppData\Local\Google\Chrome\User Data\Profile 16 传递给 Chrome binary

options = Options()
options.add_argument('--profile-directory=Profile 16')
options.add_argument("user-data-dir=C:\Users\Hana\AppData\Local\Google\Chrome\User Data\") #Path to your chrome profile
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe", options=options)

请注意,在 user-data-dir 中,您应该只传递所有配置文件的路径,然后应通过 --profile-directory

传递特定配置文件的名称(此处为配置文件 16)

您可以查看名为 PythonChromeProfile in SeleniumWebDriver-Tiny_projects on Github, Which I tested successfuly. Also you can read about creating Chrome profiles and find the path to that profile Here

的完整源代码