Python中如何将Selenium+Chrome项目打包成可执行文件?

现有软件开发语言 python3.4+selenium+谷歌浏览器,软件兼容 xp、wind7、8、10,第三方库:webbrowser,selenium, PhantomJS, PIL, Tkinter, ttk, win32con, win32api, win32com, platform, pyinstaller, shutil 找个熟悉以上库的,帮我们打包一下软件,软件打包有点小问题。会做的联系我 Q 31 290 1237
Python中如何将Selenium+Chrome项目打包成可执行文件?

4 回复

没人会做吗?付费解决这个问题哦


用PyInstaller打包Selenium+Chrome项目,核心是处理好ChromeDriver的路径。这里给你一个完整的方案:

# main.py 主程序示例
import os
import sys
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def get_chromedriver_path():
    """获取ChromeDriver路径(支持打包后运行)"""
    if getattr(sys, 'frozen', False):
        # 如果是打包后的exe,从临时解压目录找
        base_path = sys._MEIPASS
    else:
        # 开发环境,从当前目录找
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    # ChromeDriver文件路径
    if sys.platform == 'win32':
        chromedriver_name = 'chromedriver.exe'
    elif sys.platform == 'darwin':
        chromedriver_name = 'chromedriver-mac'
    else:
        chromedriver_name = 'chromedriver-linux'
    
    return os.path.join(base_path, 'drivers', chromedriver_name)

def main():
    try:
        # 获取ChromeDriver路径
        chromedriver_path = get_chromedriver_path()
        
        # 设置Chrome选项(可选)
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')  # 无头模式
        options.add_argument('--disable-gpu')
        options.add_argument('--no-sandbox')
        
        # 创建WebDriver
        service = Service(executable_path=chromedriver_path)
        driver = webdriver.Chrome(service=service, options=options)
        
        # 你的业务代码
        driver.get('https://www.baidu.com')
        print(f"页面标题: {driver.title}")
        
        # 关闭浏览器
        driver.quit()
        
    except Exception as e:
        print(f"程序运行出错: {e}")
        input("按任意键退出...")

if __name__ == '__main__':
    main()

项目结构:

your_project/
├── main.py              # 主程序
├── drivers/             # ChromeDriver目录
│   ├── chromedriver.exe      # Windows
│   ├── chromedriver-mac      # macOS
│   └── chromedriver-linux    # Linux
├── requirements.txt     # 依赖文件
└── build.spec          # PyInstaller配置文件

requirements.txt:

selenium>=4.0.0

build.spec 配置文件:

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('drivers', 'drivers')  # 将drivers目录打包进去
    ],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
)

pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.datas,
    [],
    name='your_app',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,  # 显示控制台
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

打包命令:

# 安装PyInstaller
pip install pyinstaller

# 使用spec文件打包
pyinstaller build.spec

# 或者直接打包(简单项目)
pyinstaller --onefile --add-data "drivers;drivers" main.py

关键点:

  1. ChromeDriver管理:将不同平台的ChromeDriver放在drivers目录,通过get_chromedriver_path()动态获取路径
  2. 路径处理:使用sys._MEIPASS获取打包后的临时资源目录
  3. 跨平台:根据sys.platform选择对应的ChromeDriver
  4. 无头模式:建议添加--headless选项,避免依赖GUI环境

运行打包后的程序:

  • 确保目标机器安装了Chrome浏览器
  • 直接运行生成的exe文件即可

一句话总结: 处理好ChromeDriver的路径是关键,用sys._MEIPASS获取资源目录。

用什么打包

pyinstaller

回到顶部