Pyinstaller --onefile打包后Selenium启动的Chrome窗口无法显示
问题分析与解决方法
核心问题
打包为exe后无法启动Chrome执行Selenium脚本,主要源于三个关键问题:
- 打包后
sys.executable指向生成的exe文件而非Python解释器,导致原subprocess调用无法执行py脚本 script.py和list.csv未被打包进exe,运行时系统找不到这些依赖文件- 打包后的隔离环境中,ChromeDriver的路径可能无法被Selenium正确识别
解决方案
1. 修正脚本执行逻辑(替代subprocess调用)
打包成exe后,sys.executable不再是python.exe,因此无法用它来运行py脚本。推荐将script.py的逻辑整合到gui.py中,或封装成函数直接调用:
修改gui.py的run_script函数:
def run_script(): try: # 处理基础路径 if hasattr(sys, '_MEIPASS'): base_path = sys._MEIPASS else: base_path = os.path.dirname(__file__) # 添加路径并导入script模块 sys.path.append(base_path) import script # 执行script的核心逻辑 script.main() messagebox.showinfo("Success", "Script ran successfully!") except Exception as e: error_message = f"An unexpected error occurred:\n{e}" messagebox.showerror("Error", error_message) print(error_message)
给script.py封装main函数并修正文件路径:
import time # 补充原代码缺失的time导入 import sys import os import pandas as pd from selenium.common import TimeoutException, NoSuchElementException, ElementClickInterceptedException from selenium.webdriver import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.chrome.service import Service def main(): # 处理list.csv的路径 if hasattr(sys, '_MEIPASS'): csv_path = os.path.join(sys._MEIPASS, "list.csv") else: csv_path = os.path.join(os.path.dirname(__file__), "list.csv") df = pd.read_csv(csv_path) df.cp = df.cp.astype(str) service = Service() website = 'https://google.com' for i, j in df.iterrows(): driver = webdriver.Chrome(service=service) driver.get(website) time.sleep(3) # 剩余代码保留 if __name__ == "__main__": main()
2. 打包时强制包含依赖文件
使用pyinstaller打包时,必须显式指定要包含的script.py、list.csv(若需要打包ChromeDriver也需添加):
命令行直接打包(Windows):
pyinstaller --onefile --add-data "script.py;." --add-data "list.csv;." gui.py
(Linux/macOS将分号;替换为冒号:)
用spec文件打包(更灵活):
- 生成初始spec文件:
pyinstaller --onefile gui.py - 打开
gui.spec,修改datas字段:
datas = [('script.py', '.'), ('list.csv', '.')],
- 基于spec文件重新打包:
pyinstaller gui.spec
3. 确保ChromeDriver路径可被识别
若打包后仍无法找到ChromeDriver,可手动指定其路径,并将ChromeDriver也打包进exe:
修改script.py中的Service初始化:
# 处理ChromeDriver路径 if hasattr(sys, '_MEIPASS'): driver_path = os.path.join(sys._MEIPASS, "chromedriver.exe") else: driver_path = "chromedriver.exe" # 本地运行时的路径 service = Service(driver_path)
打包时添加ChromeDriver:
pyinstaller --onefile --add-data "script.py;." --add-data "list.csv;." --add-data "chromedriver.exe;." gui.py
额外排查技巧
- 打包后打开命令行运行exe,可查看控制台输出的错误信息,快速定位问题
- 原
script.py缺失import time,运行时会触发报错,需补全 - 若使用
--onedirectory参数打包,依赖文件会直接放在输出目录,更易排查路径问题
内容的提问来源于stack exchange,提问作者Bire
相关产品推荐
相关产品推荐

