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

PyInstaller打包undetected_chromedriver后会话变量丢失问题排查

登录会话丢失原因分析

问题场景

程序流程为:通过Chrome配置文件在某网站创建账号,关闭driver后重新打开该配置文件,期望借助会话变量自动登录。但使用PyInstaller打包后的.exe程序时,账号创建正常,重新打开对应配置文件能看到浏览历史,却无法保持登录状态。

相关代码与打包命令

初始化Chrome Driver代码

def setup_chrome_driver():
    options = uc.ChromeOptions()
    date = datetime.datetime.now()
    profile = date.strftime("%H%M%S")
    userDataDir = resource_path(f".\\profiles\\profile{profile}")
    options.user_data_dir = userDataDir
    options.add_argument("--log-level=3")
    #options.add_argument("--headless=new")
    driver = uc.Chrome(options=options,version_main=109)
    return driver,profile

重新打开配置文件代码

options = uc.ChromeOptions()
userDataDir = resource_path(f".\\profiles\\profile{profile}")
options.user_data_dir = userDataDir
driver = uc.Chrome(options=options)
driver.get(url)

resource_path函数代码

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

PyInstaller打包命令

pyinstaller --noconfirm --onefile --console --add-data "C:/profiles;." --add-data  "C:/ue_installer.py"

可能的原因及解决方向

1. PyInstaller临时目录导致配置文件无法持久化

PyInstaller的onefile模式运行时,会将所有资源解压到系统临时目录(sys._MEIPASS指向的路径),程序退出后该临时目录会被自动删除。

  • 创建账号时,新生成的profile存储在临时目录下的profiles文件夹中,程序关闭后这些文件会被清理。
  • 重新运行exe时,PyInstaller会重新解压打包时自带的profiles内容到新的临时目录,此时读取的是原始空配置或旧数据,而非之前创建的包含登录会话的profile。
  • 解决方向:修改resource_path函数,将profile存储到本地固定路径(比如用户文档目录、程序所在目录),而非临时目录。例如:
    def resource_path(relative_path):
        try:
            base_path = sys._MEIPASS
        except Exception:
            # 打包后使用本地程序所在目录或固定路径
            base_path = os.path.dirname(os.path.abspath(sys.executable))
        return os.path.join(base_path, relative_path)
    

2. ChromeDriver版本不一致

初始化driver时指定了version_main=109,但重新打开driver时未指定版本,uc.Chrome可能自动匹配了其他版本的ChromeDriver。不同版本的Driver对Chrome会话存储的处理可能存在兼容性问题,导致无法读取之前的登录会话。

  • 解决方向:重新打开driver时也指定相同的版本参数:
    driver = uc.Chrome(options=options, version_main=109)
    

3. 会话文件读写异常

Chrome的登录会话(Cookies、Local Storage等)存储在profile目录的特定文件中。如果临时目录存在权限限制,导致创建账号时这些会话文件未被正确写入,或者重新打开时无法读取,就会丢失登录状态。

  • 解决方向:检查程序运行时的权限,确保Chrome能对profile目录进行读写操作;同时避免将profile存储在系统权限严格的临时目录。

4. Profile名称传递错误

创建账号时生成的profile名称是当前时间戳(%H%M%S),如果重新打开时未正确保存或传递这个名称,会导致打开错误的profile(比如默认profile或旧profile),自然无法读取目标登录会话。

  • 解决方向:确保创建账号后将profile名称持久化存储(比如写入本地配置文件),重新打开时读取该名称再定位到对应profile目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:53:14