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

部署Python脚本到Heroku时Firefox二进制文件异常问题

解决Heroku部署Firefox Selenium的二进制文件错误问题

核心问题原因

你上传的是MacOS版本的Firefox二进制文件,而Heroku运行的是Ubuntu Linux系统,两者的二进制架构、依赖库完全不兼容,所以会触发binary is not a Firefox executable错误。单独上传firefox-bin也没用,因为Mac的二进制依赖Mac系统库,Linux环境无法识别。

正确解决方案:使用Heroku Buildpack自动安装适配环境的Firefox和驱动

放弃手动上传Firefox文件,改用Heroku官方维护的buildpack来自动部署适配Linux的Firefox和Geckodriver:

  1. 添加Buildpack
    通过Heroku命令行或控制台添加两个buildpack:

    # 添加Firefox buildpack
    heroku buildpacks:add https://github.com/heroku/heroku-buildpack-firefox.git
    # 添加Geckodriver buildpack
    heroku buildpacks:add https://github.com/heroku/heroku-buildpack-geckodriver.git
    

    这些buildpack会自动在Heroku环境中安装对应版本的Firefox和驱动,并设置好环境变量。

  2. 修改Python代码适配环境
    调整代码,让它同时兼容本地Mac环境和Heroku Linux环境:

    import os
    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options as FirefoxOptions
    
    def runFirefoxSelenium():
        options = FirefoxOptions()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')  # 解决Heroku内存限制问题
        
        # 适配本地和Heroku的路径:优先读取环境变量,本地用默认Mac路径
        options.binary_location = os.environ.get('FIREFOX_BIN', './bin/Firefox.app/Contents/MacOS/firefox-bin')
        geckodriver_path = os.environ.get('GECKODRIVER_PATH', './bin/geckodriver')
        
        driver = webdriver.Firefox(options=options, executable_path=geckodriver_path)
        # 后续业务逻辑...
    

    解释:Heroku的buildpack会自动设置FIREFOX_BIN和GECKODRIVER_PATH环境变量,代码通过os.environ.get自动切换路径,本地开发时仍能使用你原来的Mac版Firefox。

  3. 额外配置检查

    • 确保requirements.txt中包含正确版本的Selenium,例如:selenium>=4.0.0
    • 提交修改后的代码和requirements.txt到Heroku

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:47:27