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

Heroku部署ChromeDriver/FirefoxDriver崩溃问题求助

问题:Heroku部署Discord价格监控机器人时Selenium驱动报错

问题描述

部署一款监控平板电脑价格、变动时向Discord发送通知的机器人,采用Heroku(GitHub学生开发包免费额度)部署,本地Chrome/Firefox驱动均可正常运行,但Heroku上出现以下问题:

  • ChromeDriver:报错SessionNotCreatedException,提示Chrome启动后退出、DevToolsActivePort文件不存在
  • FirefoxDriver:报错selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status 255,尝试使用heroku-integrated-firefox-geckodriver构建包但因Heroku 24版本不兼容(该构建包仅支持16/18/20)失败,手动部署Firefox二进制文件也未解决问题

解决方案

针对ChromeDriver的SessionNotCreatedException错误

  1. 添加Heroku官方Chrome构建包
    在Heroku项目中按顺序添加以下两个构建包:

    • https://github.com/heroku/heroku-buildpack-google-chrome.git
    • https://github.com/heroku/heroku-buildpack-chromedriver.git
      通过Heroku CLI执行命令:
    heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-google-chrome.git
    heroku buildpacks:add --index 2 https://github.com/heroku/heroku-buildpack-chromedriver.git
    
  2. 修改ChromeOptions配置
    在fetch_price函数中补充环境变量配置,解决端口和路径问题:

    import os
    
    async def fetch_price(url, whatclass):
        options = webdriver.ChromeOptions()
        # 保留原有配置,新增以下内容
        options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
        options.add_argument("--remote-debugging-port=9222")
        options.add_argument("--disable-dev-shm-usage")
        
        # 初始化驱动时指定路径
        driver = webdriver.Chrome(
            executable_path=os.environ.get("CHROMEDRIVER_PATH"),
            options=options
        )
        # 后续原有代码保持不变
    
  3. 依赖配置
    在requirements.txt中确保包含selenium和fake-useragent,构建包会自动匹配兼容的Chrome版本。

针对FirefoxDriver的Process closed status 255错误

  1. 添加兼容Heroku 24的Firefox构建包
    替换旧构建包,使用支持最新栈的社区构建包:

    heroku buildpacks:add https://github.com/moneymeets/python-poetry-buildpack.git
    heroku buildpacks:add https://github.com/dwayhs/heroku-buildpack-geckodriver.git
    heroku buildpacks:add https://github.com/dwayhs/heroku-buildpack-firefox.git
    
  2. 修改FirefoxOptions配置
    在fetch_price函数中指定二进制文件路径并补充资源限制参数:

    import os
    
    async def fetch_price(url, whatclass):
        options = Options()
        options.add_argument("-headless")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.binary_location = os.environ.get("FIREFOX_BIN")
        
        driver = webdriver.Firefox(
            executable_path=os.environ.get("GECKODRIVER_PATH"),
            options=options
        )
        # 后续原有代码保持不变
    
  3. 版本兼容性验证
    上述构建包会自动安装与Heroku 24栈兼容的Firefox和Geckodriver版本,无需手动降级Heroku栈。

额外优化建议

  • 复用驱动实例:将驱动初始化移至on_ready事件中,避免每次请求都创建新驱动,减少资源消耗
  • 添加异常捕获:在fetch_price函数中增加try-except块,处理页面加载失败、元素未找到等异常,防止机器人崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:16:02