使用Selenium ChromeDriver加载用户配置文件无法打开新Chrome窗口
问题描述
尝试使用个人用户配置文件打开新Chrome窗口,代码如下:
from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() options.add_argument("user-data-dir=C:\Users\user_name\AppData\Local\Google\Chrome\User Data\") options.add_argument("profile-directory=Profile 1") ser = Service("C:\path\to\my\chromedriver.exe") driver = webdriver.Chrome(service = ser,options=options) driver.get('https://www.google.co.in/')
已有Chrome窗口运行时,出现以下错误:
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location C:\Program Files (x86)\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Stacktrace: Backtrace: (No symbol) [0x0031DCE3] (No symbol) [0x002B39D1] (No symbol) [0x001C4DA8] (No symbol) [0x001E20BC] (No symbol) [0x001DED19] (No symbol) [0x002115AE] (No symbol) [0x0021129C] (No symbol) [0x0020ACC6] (No symbol) [0x001E6F68] (No symbol) [0x001E80CD] GetHandleVerifier [0x00593832+2506274] GetHandleVerifier [0x005C9794+2727300] GetHandleVerifier [0x005CE36C+2746716] GetHandleVerifier [0x003C6690+617600] (No symbol) [0x002BC712] (No symbol) [0x002C1FF8] (No symbol) [0x002C20DB] (No symbol) [0x002CC63B] BaseThreadInitThunk [0x768200F9+25] RtlGetAppContainerNamedObjectPath [0x77017BBE+286] RtlGetAppContainerNamedObjectPath [0x77017B8E+238]
解决方法
问题核心是Chrome不允许同一个用户数据目录被多个实例同时占用,已有窗口运行时,Selenium启动的实例无法获取目录权限导致失败,可通过两种方式解决:
方法一:添加调试端口及启动参数
在ChromeOptions中指定未被占用的调试端口,同时跳过首次运行检查,修改后代码如下:
from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() # 用原始字符串r""避免Windows路径的转义问题 options.add_argument(r"user-data-dir=C:\Users\user_name\AppData\Local\Google\Chrome\User Data") options.add_argument("profile-directory=Profile 1") # 添加调试端口及启动参数 options.add_argument("--remote-debugging-port=9222") options.add_argument("--no-first-run") options.add_argument("--no-default-browser-check") ser = Service(r"C:\path\to\my\chromedriver.exe") driver = webdriver.Chrome(service=ser, options=options) driver.get('https://www.google.co.in/')
方法二:复制独立的用户配置目录
将原Profile 1配置目录复制到新路径,让两个Chrome实例使用不同配置目录,避免冲突:
from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() # 指定复制后的新配置目录路径 options.add_argument(r"user-data-dir=C:\Users\user_name\AppData\Local\Google\Chrome\Copied User Data") options.add_argument("profile-directory=Profile 1") ser = Service(r"C:\path\to\my\chromedriver.exe") driver = webdriver.Chrome(service=ser, options=options) driver.get('https://www.google.co.in/')
内容的提问来源于stack exchange,提问作者sahshaash
相关产品推荐
相关产品推荐

