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

PyInstaller打包Selenium程序报错:session not created无法启动Chrome进程

解决PyInstaller打包Chrome Selenium应用的"session not created"错误

以下是针对问题的分步解决方案:

1. 修复硬编码路径与动态资源获取

问题分析

  • 硬编码的用户数据目录C:\Users\Urano\AppData\Local\Google\Chrome\User Data仅适用于你的账户,其他用户无法访问,且若Chrome正在运行会导致目录锁定。
  • 打包后的exe无法直接访问脚本所在目录的文件,需处理PyInstaller的临时路径。

修改代码

添加资源路径获取函数,并替换硬编码路径:

import sys
import os
import pickle
import time
import urllib.parse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_resource_path(relative_path):
    """获取打包后或脚本运行时的资源路径"""
    try:
        # PyInstaller打包后会将资源放在_MEIPASS临时目录
        base_path = sys._MEIPASS
    except Exception:
        # 直接运行脚本时使用当前目录
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def get_chrome_path():
    """动态获取Chrome浏览器路径"""
    common_paths = [
        os.path.join(os.environ.get("PROGRAMFILES"), "Google", "Chrome", "Application", "chrome.exe"),
        os.path.join(os.environ.get("PROGRAMFILES(x86)"), "Google", "Chrome", "Application", "chrome.exe"),
        os.path.join(os.environ.get("LOCALAPPDATA"), "Google", "Chrome", "Application", "chrome.exe"),
    ]
    for path in common_paths:
        if os.path.exists(path):
            return path
    return None

def run():
    # 加载messages.pkl
    messages_path = get_resource_path("messages.pkl")
    with open(messages_path, "rb") as file:
        messages = pickle.load(file)

    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    
    # 设置自定义Chrome profile(避免与用户主浏览器冲突)
    profile_dir = get_resource_path("chrome_profile")
    os.makedirs(profile_dir, exist_ok=True)
    options.add_argument(f"--user-data-dir={profile_dir}")
    options.add_argument("--profile-directory=Default")
    
    # 显式指定Chrome路径
    chrome_path = get_chrome_path()
    if not chrome_path:
        print("❌ 未找到Chrome浏览器,请先安装Chrome。")
        return
    options.binary_location = chrome_path
    
    # 添加额外稳定性参数
    options.add_argument("--disable-extensions")
    options.add_argument("--start-maximized")
    options.add_argument("--disable-infobars")
    options.add_argument("--enable-automation")

    # 使用本地chromedriver(需提前下载对应版本)
    driver_path = get_resource_path("chromedriver.exe")
    service = Service(driver_path)
    
    try:
        driver = webdriver.Chrome(service=service, options=options)
    except Exception as e:
        print(f"❌ 启动Chrome失败: {e}")
        return

    wait = WebDriverWait(driver, 30)

    print("Abriendo WhatsApp Web...")
    driver.get("https://web.whatsapp.com")
    input("Escaneá el código QR y presioná ENTER cuando WhatsApp Web esté cargado...\n")

    for phone, message in messages:
        try:
            print(f"\n📨 Preparando mensaje para {phone}")
            encoded_message = urllib.parse.quote(message)
            url = f"https://web.whatsapp.com/send?phone={phone}&text={encoded_message}"
            driver.get(url)
            print("🔄 Esperando que cargue el campo de texto...")
            message_box = wait.until(
                EC.presence_of_element_located((By.XPATH, '//div[@data-tab="10"]'))
            )
            print("✅ Campo de texto localizado")

            time.sleep(2)

            message_box.send_keys(Keys.ENTER)
            print(f"✅ Mensaje enviado a {phone}")

            time.sleep(3)

        except Exception as e:
            print(f"❌ Error al enviar mensaje a {phone}: {e}")
            continue

    driver.quit()
    print("\n✅ Todos los mensajes procesados.")

if __name__ == "__main__":
    run()

2. 准备打包资源

  • 下载与你的Chrome版本(135.0.7049.84)完全匹配的chromedriver.exe,将其放在项目根目录。
  • 确保messages.pkl也在项目根目录。

3. 使用PyInstaller打包

命令行打包(单文件)

运行以下命令生成单文件exe:

pyinstaller --onefile --add-data "chromedriver.exe;." --add-data "messages.pkl;." main.py
  • --onefile:生成单个exe文件。
  • --add-data:将指定文件打包进exe,运行时自动提取到临时目录。

命令行打包(多文件目录)

若单文件模式仍有问题,可尝试多文件模式(更稳定):

pyinstaller --onedir --add-data "chromedriver.exe;." --add-data "messages.pkl;." main.py

生成的exe会在dist/main目录下,需将整个目录分发给用户。

4. 测试打包后的应用

  • 运行生成的exe文件,检查是否能正常启动Chrome并发送消息。
  • 若仍有问题,尝试以管理员权限运行exe,或关闭用户正在运行的Chrome实例(避免profile冲突)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:47:32