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

使用PyInstaller打包含Selenium与Pandas的Python程序遇报错求助

解决PyInstaller打包Selenium脚本时找不到getAttribute.js的问题

以下是几个可行的解决方向:

  • 手动添加缺失的JS文件到打包资源
    找到你Anaconda环境中Selenium的安装目录,定位getAttribute.js文件(通常路径类似Lib/site-packages/selenium/webdriver/common),然后在PyInstaller打包命令中用--add-data参数将该文件包含进去:

    • Windows系统:
      pyinstaller --add-data "C:\你的Anaconda路径\envs\你的环境名\Lib\site-packages\selenium\webdriver\common\getAttribute.js;." 你的脚本名.py
      
    • Mac/Linux系统:
      pyinstaller --add-data "/你的Anaconda路径/envs/你的环境名/lib/pythonX.X/site-packages/selenium/webdriver/common/getAttribute.js:." 你的脚本名.py
      
  • 动态获取Selenium内置文件路径
    修改脚本中调用getAttribute.js的逻辑,通过Selenium的安装目录动态定位该文件,示例代码:

    import os
    import selenium
    
    # 获取Selenium的安装目录
    selenium_dir = os.path.dirname(selenium.__file__)
    js_file_path = os.path.join(selenium_dir, "webdriver", "common", "getAttribute.js")
    
    # 后续使用js_file_path来调用该文件
    
  • 通过.spec文件配置打包资源
    生成PyInstaller的.spec配置文件:

    pyinstaller --name 你的应用名 你的脚本名.py
    

    打开生成的.spec文件,在datas列表中添加JS文件的映射:

    datas = [
        ('/路径/to/getAttribute.js', 'selenium/webdriver/common'),
        # 同时可以添加ChromeDriver的路径,比如:
        ('/路径/to/chromedriver', '.')
    ]
    

    然后用.spec文件重新打包:

    pyinstaller 你的应用名.spec
    
  • 确保ChromeDriver正确打包
    打包时不要忘记将ChromeDriver包含进去,用--add-binary参数(Windows下是.exe文件),同时脚本中要通过sys._MEIPASS动态获取打包后的ChromeDriver路径:

    import sys
    import os
    from selenium import webdriver
    
    def get_chromedriver_path():
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, 'chromedriver.exe')  # Windows用.exe,Mac/Linux去掉
        else:
            return 'chromedriver.exe'
    
    driver = webdriver.Chrome(executable_path=get_chromedriver_path())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:10:31