MacOS M1环境下如何在Selenium中加载指定Firefox配置文件
解决Selenium加载指定Firefox配置文件失败的问题
问题场景
MacOS Darwin M1环境下,使用Selenium 4.12.0 + webdriver-manager 4.0.0,尝试加载指定Firefox配置文件时,程序始终创建并使用临时配置文件(日志中可见类似"-profile" "/var/folders/0k/hz9yngm56nz1htdc3c3t3d0c0000gn/T/rust_mozprofileecFA3Z"的临时路径),而非目标配置文件。原代码如下:
profile_path = '/Users/mymachine/Library/Application Support/Firefox/Profiles/specificprofile.default' options = webdriver.FirefoxOptions() options.set_preference('profile', profile_path) service = FirefoxService(GeckoDriverManager().install()) driver = webdriver.Firefox(service=service, options=options)
直接指定GeckoDriver路径的尝试同样无效。
问题原因
Selenium 4.x版本中,通过options.set_preference('profile', 路径)的方式已不再支持加载本地Firefox配置文件,该设置无法被正确识别,因此Selenium会默认创建临时配置文件启动Firefox。
解决方案
改用FirefoxProfile类实例化目标配置文件,并将其赋值给FirefoxOptions的profile属性,具体代码如下:
from selenium import webdriver from selenium.webdriver.firefox.service import FirefoxService from webdriver_manager.firefox import GeckoDriverManager from selenium.webdriver.firefox.firefox_profile import FirefoxProfile # 替换为你的目标配置文件路径 profile_path = '/Users/mymachine/Library/Application Support/Firefox/Profiles/specificprofile.default' # 实例化FirefoxProfile对象 firefox_profile = FirefoxProfile(profile_path) options = webdriver.FirefoxOptions() # 将配置文件绑定到options options.profile = firefox_profile # 初始化服务与驱动 service = FirefoxService(GeckoDriverManager().install()) driver = webdriver.Firefox(service=service, options=options)
额外注意事项
- 确保目标配置文件路径准确,路径中的
specificprofile.default是Firefox实际生成的配置文件夹名称(可通过about:profiles在Firefox中查看) - 启动代码前关闭所有正在运行的Firefox进程,避免配置文件被占用导致加载失败
- 若仍存在问题,可尝试添加
options.add_argument('-no-remote'),强制Firefox启动独立实例,避免与现有进程冲突
内容的提问来源于stack exchange,提问作者MrT77
相关产品推荐
相关产品推荐

