首页 > 解决方案 > Selenium 不使用默认 Chrome 配置文件

问题描述

Selenium 不会加载我的默认 Chrome 配置文件,我不知道为什么。我已经尝试过配置文件 1 和默认配置文件,但出现相同的错误(如下)。我已通过任务管理器确认所有 Chrome 窗口在运行此代码之前都已关闭。有什么想法吗?

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import os
os.system("taskkill /f /im geckodriver.exe /T")
os.system("taskkill /f /im chromedriver.exe /T")
os.system("taskkill /f /im IEDriverServer.exe /T")
os.system("taskkill /f /im chrome.exe /T")

driver2 = r"C:\Users\xxx\.wdm\drivers\chromedriver\87.0.4280.20\win32\chromedriver.exe"
options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\\Users\xxx\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1")
driver = webdriver.Chrome(executable_path=driver2, chrome_options=options)
driver.get("https://www.google.co.in")

Traceback (most recent call last):
  File "C:\Users\xxx\OneDrive\Python\pyReportRun.py", line 16, in <module>
    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
  File "C:\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 76, in __init__
    RemoteWebDriver.__init__(
  File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python38\lib\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: Could not remove old devtools port file. Perhaps the given user-data-dir at C:\Users\xxx\AppData\Local\Google\Chrome\User Data\Profile 1 is still attached to a running Chrome or Chromium process

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

[1]:https://i.stack.imgur.com/qf1Rr.png

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

标签: pythonseleniumgoogle-chromeselenium-chromedriverchrome-profile

解决方案


chrom_options.add_argument("user-data-dir=C:\\Users\robert.car\\AppData\\Local\\Google\\Chrome\\User Data")

chrom_options.add_argument("profile-directory=Profile 1")

user-data-dir 将 profile 视为 default ,您不必指定 . 如果它是其他东西通过 profile-directory 参数指定它

创建配置文件的步骤:

打开:地址栏中的 chrome://version

在此处输入图像描述

将用户 dir 文件夹完全复制到例如 c:\tmp\newdir

打开复制的用户数据(newdir)并搜索名为 Default 的文件夹。这是配置文件文件夹。

默认文件夹重命名为“配置文件 1”

现在使用这个:

chrom_options.add_argument("user-data-dir=c:\\tmp\\newdir")

chrom_options.add_argument("profile-directory=Profile 1")

推荐阅读