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

voi*_*ter 2 python selenium google-chrome selenium-chromedriver selenium-webdriver

自首次报道以来已经过去了 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()
Run Code Online (Sandbox Code Playgroud)

当它启动时,转到 chrome://version/ 并查看:

配置文件路径 C:\Users\USERCU~1\AppData\Local\Temp\scoped_dir13280_930640861\Default

为了设置某些配置文件,我尝试了这里的代码How to load default profile in Chrome using Python Selenium Webdriver?

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)
Run Code Online (Sandbox Code Playgroud)

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

配置文件路径 C:\Users\usercuhuh\AppData\Local\Google\Chrome\User Data\Profile 16\Default

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

BzH*_*BzH 5

首先


将您的 ChromeDriver 更新到最新版本


(这部分是强制性的)。然后将两个参数--profile-directory=Profile 1和传递user-data-dir=C:\\Users\\user123\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 16给 Chrome 二进制文件

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)
Run Code Online (Sandbox Code Playgroud)

请注意,user-data-dir您应该只传递所有配置文件的路径,然后应传递特定配置文件的名称(此处为配置文件 16)--profile-directory

您可以在 Github 上的SeleniumWebDriver-Tiny_projects中查看名为PythonChromeProfile的完整源代码,我已经测试成功。您还可以阅读有关创建 Chrome 配置文件的信息,并在此处找到该配置文件的路径