You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Python报错User directory already in use,单实例运行仍异常

问题:Selenium启动Chrome实例时提示用户数据目录被占用

我需要同时运行多个Chrome实例并保存每个实例的数据,通过当前时间生成了唯一的用户文件夹路径,但运行单个实例时仍报错目录被占用,Chrome直接崩溃。

示例代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import os
import time

profile_path = os.path.join(os.getcwd(), f"chrome_profiles/{time.strftime('%m.%d.%Y_%H.%M.%S')}")
if not os.path.isdir(profile_path):
    os.makedirs(profile_path)

chrome_options = Options()
chrome_options.add_argument(f"--user-data-dir={profile_path}")
chrome_options.add_argument(f"--profile-directory=Default")


service = Service() 
driver = webdriver.Chrome(service=service, options=chrome_options)

driver.get("https://www.google.com")

报错信息

SessionNotCreatedException: Message: session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir

问题原因

问题出在--profile-directory=Default参数上:你创建的新user-data-dir目录下默认不存在Default子目录,Chrome启动时会尝试初始化这个目录,但该过程与Selenium的启动逻辑冲突,导致误报“目录被占用”,最终引发Chrome崩溃。

解决方案

两种可行方式二选一即可:

方式1:移除--profile-directory=Default参数

让Chrome自动在新的user-data-dir下创建默认配置目录,无需手动指定:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import os
import time

profile_path = os.path.join(os.getcwd(), f"chrome_profiles/{time.strftime('%m.%d.%Y_%H.%M.%S')}")
if not os.path.isdir(profile_path):
    os.makedirs(profile_path)

chrome_options = Options()
chrome_options.add_argument(f"--user-data-dir={profile_path}")

service = Service() 
driver = webdriver.Chrome(service=service, options=chrome_options)

driver.get("https://www.google.com")

方式2:手动创建Default子目录

先在生成的profile_path下创建Default子目录,再指定--profile-directory=Default参数:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import os
import time

profile_path = os.path.join(os.getcwd(), f"chrome_profiles/{time.strftime('%m.%d.%Y_%H.%M.%S')}")
default_dir = os.path.join(profile_path, "Default")
if not os.path.isdir(default_dir):
    os.makedirs(default_dir)

chrome_options = Options()
chrome_options.add_argument(f"--user-data-dir={profile_path}")
chrome_options.add_argument(f"--profile-directory=Default")

service = Service() 
driver = webdriver.Chrome(service=service, options=chrome_options)

driver.get("https://www.google.com")

内容的提问来源于stack exchange,提问作者user9102437

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:03:11