Python Selenium多Chrome配置文件启动失败的问题排查与修复咨询
问题重现
执行以下代码时触发selenium.common.exceptions.WebDriverException错误,无法同时启动两个独立的Chrome实例:
from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.chrome.service import Service USER_DATA_DIR = r'C:\custom_chrome' if __name__ == '__main__': option = Options() option.add_argument(f"user-data-dir={USER_DATA_DIR}") option.add_argument(f"profile-directory=Profile 1") option.add_argument('--no-sandbox') driver = webdriver.Chrome(service=Service('chromedriver.exe'), options=option) option2 = Options() option2.add_argument(f"user-data-dir={USER_DATA_DIR}") option2.add_argument(f"profile-directory=Profile 2") option2.add_argument('--no-sandbox') # 错误:此处误用了option参数,应该是option2 driver2 = webdriver.Chrome(service=Service('chromedriver.exe'), options=option) driver.get('google.com') driver2.get('google.com') print('aaaa')
错误信息
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\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
已尝试方案
- 使用多进程,为ChromeDriver创建两个文件分别调用;
- 将Chrome作为子进程启动,通过不同端口的debuggerAddress附加调试模式。
版本信息
- selenium 4.8.2
- Chrome 115.0.5790.110
修复步骤
1. 修正参数误用错误
首先修复代码中driver2实例化时的参数错误,将options=option改为options=option2。
2. 添加独立端口配置
即使修正参数,Chrome默认会共享调试端口,导致第二个实例启动失败。需要为每个Chrome实例指定独立的远程调试端口,同时添加--disable-dev-shm-usage参数避免资源限制(Windows/Linux环境均兼容)。
修正后的完整代码:
from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.chrome.service import Service USER_DATA_DIR = r'C:\custom_chrome' if __name__ == '__main__': # 第一个实例:Profile 1,使用端口9222 option = Options() option.add_argument(f"user-data-dir={USER_DATA_DIR}") option.add_argument(f"profile-directory=Profile 1") option.add_argument('--no-sandbox') option.add_argument('--disable-dev-shm-usage') option.add_argument('--remote-debugging-port=9222') driver = webdriver.Chrome(service=Service('chromedriver.exe'), options=option) driver.get('https://google.com') # 第二个实例:Profile 2,使用端口9223 option2 = Options() option2.add_argument(f"user-data-dir={USER_DATA_DIR}") option2.add_argument(f"profile-directory=Profile 2") option2.add_argument('--no-sandbox') option2.add_argument('--disable-dev-shm-usage') option2.add_argument('--remote-debugging-port=9223') driver2 = webdriver.Chrome(service=Service('chromedriver.exe'), options=option2) driver2.get('https://google.com') print('两个Chrome实例启动成功')
3. 验证配置文件有效性
确保C:\custom_chrome目录下存在Profile 1和Profile 2两个子目录,若不存在,可手动创建或通过Chrome浏览器的配置管理界面生成对应配置文件。
内容的提问来源于stack exchange,提问作者김재민

