Windows环境下Python Selenium如何正确加载Firefox配置文件
问题修复方案
该问题核心是代码写法不符合Selenium 4.x及以上版本的接口规范,旧版直接传入FirefoxProfile实例、使用executable_path指定驱动路径的接口均已被废弃,是导致配置加载失败、驱动连接异常的核心原因。
修复步骤
- 补全缺失的依赖导入,确保正确导入Firefox专属的Options类
- 不再直接实例化
FirefoxProfile,改为通过options.profile绑定配置文件路径 - 使用Service类指定geckodriver路径,替换废弃的
executable_path参数
修正后可运行代码
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service options = Options() options.headless = False # 直接通过options.profile传入配置文件路径即可,不需要单独实例化FirefoxProfile options.profile = r'C:\Users\xxXX\AppData\Local\Mozilla\Firefox\Profiles\y73h6ogb.default-release' # 用Service指定驱动路径 service = Service(executable_path='geckodriver/geckodriver.exe') driver = webdriver.Firefox(service=service, options=options) driver.get(URL)
额外排查要点
- 确认Firefox浏览器版本与geckodriver版本匹配,版本不兼容会直接触发驱动连接丢失问题
- 确认填写的配置文件路径真实存在,无拼写错误
- 运行代码前关闭所有已打开的Firefox窗口,避免进程占用配置文件导致加载失败
内容的提问来源于stack exchange,提问作者Uniextra
相关产品推荐
相关产品推荐

