如何解决含Selenium与chromedriver的Python脚本打包exe失败问题?
Python爬虫打包EXE故障排查方案
问题描述
我是Python新手,想把带输入交互的网页爬虫脚本打包成exe给他人使用,但打包后无法正常运行:
- 用PyInstaller指定.spec文件打包,生成的exe运行无任何反应
- 用auto-py-to-exe打包,能进入参数输入环节,但Chrome启动失败后程序直接关闭,看不到错误信息
我使用的相关文件与命令
执行命令
pyinstaller webscraper.spec webscraper.py
.spec文件内容
# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['webscraper.py'], pathex=['C:\\Users\\myname\\Python\\webscraper'], binaries=[('C:\\Program Files (x86)\\chromedriver.exe', '***.\\selenium\\webdriver**')], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='webscraper', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='webscraper', )
爬虫脚本代码
import os import time import math import pandas as pd import win32com.client as win32 from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By # load Excel file into python excel_folder = input("Input excel folder path: ") os.chdir(excel_folder) excel_file = input("Input excel filename (with extension): ") sheet_name = input("Input sheet name: ") part_column = input("Input part number column name: ") price_column = "Vendor Price" batch_column = "Batch" qty_column = "Vendor QTY" total_column = "Total Price" totalqty_column = "Total QTY" xldata = pd.read_excel(excel_file, sheet_name=sheet_name) # chrome driver path s = Service(r"C:\Program Files (x86)\chromedriver.exe") driver = webdriver.Chrome(service=s) # get total row count (index=None for rows without labels) df = pd.DataFrame(xldata, index=None) rows = len(df.axes[0]) # close Excel if the file is open xapp = win32.DispatchEx("Excel.Application") xl = win32.GetActiveObject("Excel.Application") for wb in xl.Workbooks: if os.path.dirname(wb.FullName) == excel_folder: wb.Close(True) xapp.Quit() # loop through all part numbers in worksheet for row_curser in range(0, rows): xl_value1 = xldata[part_column][row_curser] xl_value2 = xldata[totalqty_column][row_curser] # go to part number webpage page = r"https://www.mcmaster.com/" + xl_value1 + r'/' driver.get(page) driver.maximize_window() # wait for page to load before locating elements time.sleep(1) # locate price price = driver.find_element(By.CLASS_NAME, "PrceTxt") # split price and UoM pt = price.text s = pt.split(' ') cost = s[0] batch = ' '.join(s[1:]) qty = s[-1] # transform each to qty of 1 if qty == 'Each': qty = 1 else: qty = qty # get total price costsplit = cost.split('$') total = math.ceil(float(xl_value2) / float(qty)) * float(costsplit[1]) # write prices to Excel df.at[row_curser, price_column] = cost df.at[row_curser, batch_column] = batch df.at[row_curser, qty_column] = qty df.at[row_curser, total_column] = total df.to_excel(excel_file, index=False) # close web browser driver.quit() # open Excel file xlapp = win32.DispatchEx("Excel.Application") xlapp.WindowState = -4137 xlapp.Visible = 1 wb = xlapp.workbooks.open(excel_folder + "\\" + excel_file)
问题排查与修复步骤
1. 先解决看不到错误信息的问题
- 用auto-py-to-exe打包时,务必勾选Console Window选项,程序崩溃时控制台不会立即关闭,能直接查看报错内容。
- 用PyInstaller打包后,不要双击exe,而是打开命令提示符,进入exe所在目录,手动执行
webscraper.exe,命令行会输出具体错误。
2. 修复ChromeDriver路径问题(核心故障)
脚本硬编码了ChromeDriver的绝对路径,其他用户电脑不一定有这个路径;且.spec文件的binaries配置路径错误:
- 修正.spec文件的binaries配置,将ChromeDriver打包到exe同目录:
binaries=[('C:\\Program Files (x86)\\chromedriver.exe', '.')], - 修改脚本里的ChromeDriver路径,自动读取打包后的路径:
# 获取当前exe所在目录 current_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接ChromeDriver路径 driver_path = os.path.join(current_dir, 'chromedriver.exe') s = Service(driver_path) driver = webdriver.Chrome(service=s)
3. 补充隐藏依赖与调整打包配置
- 在.spec文件的Analysis部分添加隐藏依赖,PyInstaller可能无法自动识别这些库:
hiddenimports=['pandas', 'win32com.client', 'selenium.webdriver.chrome.options'], - 关闭UPX压缩,部分二进制文件(如ChromeDriver)被压缩后会失效,将.spec文件里的
upx=True改为upx=False。
4. 修复Excel操作的兼容性问题
win32.GetActiveObject("Excel.Application")会在无Excel进程时报错,添加异常处理:try: xl = win32.GetActiveObject("Excel.Application") except: xl = win32.DispatchEx("Excel.Application")- 将
df.to_excel(excel_file, index=False)移到循环外,避免循环内反复保存文件,减少冲突风险。
5. 重新打包的正确流程
- 删除之前生成的build、dist文件夹和旧.spec文件
- 执行
pyinstaller --onefile --console webscraper.py生成新的.spec文件 - 修改新.spec文件,添加binaries和hiddenimports配置
- 执行
pyinstaller webscraper.spec完成最终打包
内容的提问来源于stack exchange,提问作者scorbin
相关产品推荐
相关产品推荐

