如何在Chrome已打开配置文件时启动Selenium ChromeDriver脚本
解决ChromeDriver与已有Chrome实例冲突的方案
核心思路:使用独立的Chrome用户数据目录
让Selenium驱动的Chrome使用完全独立的用户配置文件夹,和日常使用的Chrome配置分隔开,两者就能同时运行互不干扰。
步骤1:创建独立的用户数据目录
Windows系统
- 打开命令提示符(CMD),执行以下命令创建新配置:
首次运行会打开全新Chrome窗口,你可以在这里安装所需扩展、设置偏好,完成后关闭窗口即可。chrome.exe --user-data-dir="C:\ChromeSeleniumProfile" --profile-directory="SeleniumProfile"
Mac OS系统
- 打开终端,执行以下命令:
系统会在用户目录下创建/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="$HOME/ChromeSeleniumProfile" --profile-directory="SeleniumProfile"ChromeSeleniumProfile文件夹,完成配置设置后关闭Chrome。
步骤2:在Selenium脚本中指定配置目录
在代码里通过ChromeOptions指向刚才创建的独立目录,以下是主流语言的示例:
Python示例
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # Windows路径 chrome_options.add_argument(r"--user-data-dir=C:\ChromeSeleniumProfile") chrome_options.add_argument("--profile-directory=SeleniumProfile") # Mac路径(注释掉Windows代码后启用) # chrome_options.add_argument(f"--user-data-dir={os.environ['HOME']}/ChromeSeleniumProfile") # chrome_options.add_argument("--profile-directory=SeleniumProfile") driver = webdriver.Chrome(options=chrome_options) driver.get("https://www.example.com")
Java示例
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class ChromeTest { public static void main(String[] args) { ChromeOptions options = new ChromeOptions(); // Windows路径 options.addArguments("--user-data-dir=C:\\ChromeSeleniumProfile"); options.addArguments("--profile-directory=SeleniumProfile"); // Mac路径(注释掉Windows代码后启用) // options.addArguments("--user-data-dir=" + System.getProperty("user.home") + "/ChromeSeleniumProfile"); // options.addArguments("--profile-directory=SeleniumProfile"); ChromeDriver driver = new ChromeDriver(options); driver.get("https://www.example.com"); } }
额外提示
- 独立配置里提前装好需要的扩展,后续Selenium启动时会自动加载,无需在脚本中重复配置。
- 如需多个测试环境,可创建多个
profile-directory(如TestProfile1、TestProfile2),在脚本中切换即可。
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

