使用Python+Selenium启动Firefox浏览器失败问题求助
解决Ubuntu下Snap安装Firefox搭配Selenium启动失败问题
问题核心分析
从geckodriver日志可见关键错误:
/snap/firefox/current/firefox.launcher: 46: exec: /snap/pycharm-community/310/usr/lib/firefox/firefox: not found
Snap版Firefox的启动脚本被错误指向了PyCharm的Firefox路径,导致启动失败返回状态码127。
解决方案
方案1:代码中直接指定Firefox二进制路径
在初始化webdriver时,通过FirefoxOptions明确指定Snap安装的Firefox实际路径:
from selenium import webdriver from selenium.webdriver.firefox.service import Service as FirefoxService from selenium.webdriver.firefox.options import Options as FirefoxOptions # 配置Firefox选项,指定二进制文件路径 firefox_options = FirefoxOptions() firefox_options.binary_location = "/snap/firefox/current/usr/lib/firefox/firefox" # 初始化服务(可选择本地geckodriver或webdriver-manager) service = FirefoxService(executable_path="./geckodriver") # 若使用webdriver-manager,替换为以下两行: # from webdriver_manager.firefox import GeckoDriverManager # service = FirefoxService(executable_path=GeckoDriverManager().install()) # 启动浏览器 browser = webdriver.Firefox(service=service, options=firefox_options) browser.get("http://selenium.dev/")
方案2:修复错误的环境变量
检查是否存在被错误设置的FIREFOX_BIN环境变量:
echo $FIREFOX_BIN
若输出为/snap/pycharm-community/310/usr/lib/firefox/firefox,执行以下命令临时取消该变量:
unset FIREFOX_BIN
如需永久生效,找到设置该变量的配置文件(如~/.bashrc、~/.zshrc或PyCharm启动脚本),删除对应的export FIREFOX_BIN=...行,重启终端后生效。
方案3:验证修复效果
在终端直接运行以下命令,测试Firefox Marionette模式是否能正常启动:
/snap/firefox/current/firefox.launcher --marionette
若能正常打开Firefox,说明路径问题已解决,再运行Selenium代码即可正常工作。
内容的提问来源于stack exchange,提问作者Bigya Pradhan
相关产品推荐
相关产品推荐

