Ubuntu 22.04下Python Selenium多Firefox窗口启动报错求助
解决Selenium启动多个Firefox窗口时的SessionNotCreatedException错误
核心问题
你遇到的Session is already started错误,根源是重复使用了同一个Service实例。Firefox的geckodriver Service对象与单个会话绑定,无法被多个webdriver.Firefox实例共享,这和Chrome的Service实现逻辑不同。
修复方案
为每个Firefox实例创建独立的Service对象,同时修正列表初始化的写法(避免索引赋值的潜在问题),以下是可行的代码示例:
from selenium import webdriver from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_profile import FirefoxProfile geckodriver_path = "/snap/bin/geckodriver" profile_dir = "/path/to/your/profile/parent/dir/" # 替换为你的profile根目录 profile_names = ["profile_0", "profile_1", ..., "profile_9"] # 10个独立的profile名称 drivers = [] for name in profile_names: # 为每个实例创建专属的Service service = Service(executable_path=geckodriver_path) options = Options() # 配置独立Profile(二选一即可) # 方式1:使用FirefoxProfile对象 profile = FirefoxProfile(f"{profile_dir}{name}") options.profile = profile # 方式2:直接通过命令行参数指定 # options.add_argument(f'-profile {profile_dir}{name}') driver = webdriver.Firefox(service=service, options=options) drivers.append(driver)
额外说明
- 列表初始化修正:原代码中
options = [] * 10和drivers = [] * 10的写法虽然能工作,但使用append动态添加元素更简洁,也避免了索引越界的潜在风险。 - Profile独立性验证:确保每个
profile_dir + name对应的文件夹是唯一的,且拥有读写权限。单个实例能正常启动已说明路径合法,只需保证多实例路径不重复即可。 - 进程清理:使用完毕后,需逐个关闭所有driver实例,避免残留Firefox进程:
for driver in drivers: driver.quit()
内容的提问来源于stack exchange,提问作者search_explore
相关产品推荐
相关产品推荐

