Debian12下Selenium调用已有Chrome配置文件失败求助
在Debian 12上用Selenium调用已有Chrome Profile的解决方案
问题分析
- 第一个报错
DevToolsActivePort file doesn't exist:目标Profile被正在运行的Chrome实例占用,或缺少Linux环境下的必要启动参数。 - 第二个报错
Can not connect to the Service /opt/google/chrome/chrome:错误将Chrome浏览器路径作为ChromeDriver路径传入,Service需要的是ChromeDriver可执行文件路径。
解决步骤
匹配Chrome与ChromeDriver版本
先查看Chrome版本:google-chrome --version下载对应版本的ChromeDriver,将其放到系统可执行路径(如
/usr/local/bin/),或在代码中指定正确路径。关闭所有Chrome实例
确保没有进程占用目标Profile,执行命令:pkill -f google-chrome修正代码配置
以下是基础修正版本:from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options() # 指定已有Profile的目录 options.add_argument("--user-data-dir=/home/sajjad/.config/google-chrome") options.add_argument('--profile-directory=Default') # Linux环境下必备参数,解决权限与资源限制问题 options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') # 可选:防止Chrome启动后自动退出 options.add_experimental_option("detach", True) # 正确指定ChromeDriver路径(示例路径,需根据实际情况调整) service = Service(executable_path="/usr/local/bin/chromedriver") driver = webdriver.Chrome(options=options, service=service) driver.get("https://google.com/") print(driver.current_url)若想自动管理ChromeDriver,可使用
webdriver-manager:
先安装依赖:pip install webdriver-manager代码修改为:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service options = Options() options.add_argument("--user-data-dir=/home/sajjad/.config/google-chrome") options.add_argument('--profile-directory=Default') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_experimental_option("detach", True) driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) driver.get("https://google.com/") print(driver.current_url)
额外注意事项
- 检查
/home/sajjad/.config/google-chrome目录权限,确保运行代码的用户拥有读写权限。 - 运行代码前不要手动打开使用该Profile的Chrome窗口,避免进程冲突。
内容的提问来源于stack exchange,提问作者Sajjad Saharkhan
相关产品推荐
相关产品推荐

