【问题标题】:How to use certain Chrome profile with selenium python?如何将某些 Chrome 配置文件与 selenium python 一起使用?
【发布时间】:2021-09-19 18:48:46
【问题描述】:

距离第一次报道已经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/ 看看:

配置文件路径 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)

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

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

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

【问题讨论】:

    标签: python selenium google-chrome selenium-webdriver selenium-chromedriver


    【解决方案1】:

    首先


    将您的 ChromeDriver 更新到最新版本


    (此部分为必填项)。 然后将两个参数 --profile-directory=Profile 1user-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)
    

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

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

    【讨论】:

    • 这个:请注意,在 user-data-dir 中,您应该只传递所有配置文件的路径,然后应通过 --profile-directory 传递特定配置文件的名称(此处为 Profile 16)跨度>
    • 谢谢!我还安装了 selenium 4.0.0rc1,因为它实现了 CDP(我的目的是 stackoverflow.com/questions/69243355/…)但它的文档是空的:selenium.dev/documentation/support_packages/chrome_devtools 也许你能建议我在哪里找到它?
    • 我只知道你创建了一个新线程。让我看看
    • 我还注意到一件事:如果您同时使用例如配置文件 1 和配置文件 16,您会收到错误:selenium.common.exceptions.InvalidArgumentException:消息:无效参数:用户数据目录已在使用中,请为 --user-data-dir 参数指定一个唯一值,或者不要使用 --user-data-dir 并且仅启动指定的配置文件但不执行更多操作。因此,您应该将要使用的所需配置文件的文件夹放入不同的 --user-data-dir
    • 我在user-data-dir 路径中有两个配置文件,只调用--profile-directory 中的配置文件1。没有为我提出错误
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2016-05-31
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多