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

如何通过Python Selenium指定使用特定Firefox二进制文件(兼容多浏览器)

嘿,这个问题我之前也碰到过,其实核心就是告诉Selenium去哪找你指定的浏览器实例,我给你一步步拆解:

针对Firefox的具体解决方法

在你的环境里(Selenium 3.11.0 + Firefox 59),有两种常用方式指定非默认的Firefox实例:

方式1:使用FirefoxBinary类

直接指定自定义Firefox的二进制执行文件路径(注意Mac下的.app包只是容器,实际执行文件在Contents/MacOS目录下):

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

# 替换成你另一个Firefox实例的实际路径
custom_firefox_path = "/Users/你的用户名/目标文件夹/Firefox.app/Contents/MacOS/firefox-bin"
binary = FirefoxBinary(custom_firefox_path)

# 如果GeckoDriver不在系统PATH里,记得指定它的路径
driver = webdriver.Firefox(firefox_binary=binary, executable_path="/path/to/geckodriver")

方式2:使用Options类(更推荐,适配后续版本)

用FirefoxOptions来配置二进制路径,这种写法更统一,也和其他浏览器的配置逻辑一致:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
# 设置自定义Firefox的二进制路径
options.binary_location = "/Users/你的用户名/目标文件夹/Firefox.app/Contents/MacOS/firefox-bin"

# 初始化driver,同样注意GeckoDriver的路径
driver = webdriver.Firefox(options=options, executable_path="/path/to/geckodriver")
推广到其他浏览器的通用思路

其实所有主流浏览器的实现逻辑都是一致的:通过对应的Options类指定浏览器二进制文件的绝对路径,让Selenium跳过系统默认的浏览器实例。

Chrome示例

假设你有另一个Chrome实例,路径类似这样:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.binary_location = "/Users/你的用户名/目标文件夹/Google Chrome.app/Contents/MacOS/Google Chrome"
driver = webdriver.Chrome(options=options, executable_path="/path/to/chromedriver")

Safari示例

Safari的配置逻辑类似,不过要注意SafariDriver是系统自带的(对应Selenium的版本):

from selenium import webdriver
from selenium.webdriver.safari.options import Options

options = Options()
options.binary_location = "/Users/你的用户名/目标文件夹/Safari.app/Contents/MacOS/Safari"
driver = webdriver.Safari(options=options)
几个关键注意事项
  • 一定要指定浏览器可执行文件的绝对路径,而不是.app包本身,Mac下的.app本质是文件夹,真正的执行程序在Contents/MacOS子目录里。
  • 确保你的驱动程序(GeckoDriver/ChromeDriver)和对应浏览器的版本兼容,比如你用的GeckoDriver 0.20.1搭配Firefox 59是完全没问题的。
  • 如果驱动程序已经添加到系统的PATH环境变量中,可以省略executable_path参数,Selenium会自动找到它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:24:19