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

打包Python脚本为EXE后Selenium无法识别Chrome Portable路径的问题

解决PyInstaller打包EXE后无法找到Chrome便携版的问题

核心问题原因

PyInstaller打包成EXE后,运行时会将程序文件解压到系统临时目录(比如C:\Users\whuang\AppData\Local\Temp\_MEIxxxxxx\),你原来用os.path.dirname(os.path.abspath(__file__))获取的路径是这个临时目录,而非EXE文件实际所在的目录,导致代码找不到你放在EXE同目录下的Chrome便携版文件夹。

解决方案

1. 修正运行目录的获取方式

用sys.executable来获取当前运行的EXE文件路径,再提取其所在目录,替换原来的current_directory赋值逻辑。

2. 修改后的完整代码

import os
import sys
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 获取EXE实际所在目录
current_directory = os.path.dirname(os.path.abspath(sys.executable))
driver_path = os.path.join(current_directory, "chromedriver.exe")
# 用os.path.join逐层拼接路径,避免硬编码斜杠的兼容性问题
chrome_path = os.path.join(current_directory, "GoogleChromePortable_114.0.5735.91", "App", "Chrome-bin", "chrome.exe")
profile_path = os.path.join(current_directory, "GoogleChromePortable_114.0.5735.91", "Data", "profile", "Default")

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--remote-debugging-port=9222")
chrome_options.add_argument(f"--user-data-dir={profile_path}")
chrome_service = Service(driver_path)
chrome_options.binary_location = chrome_path
browser = webdriver.Chrome(options=chrome_options, service=chrome_service)

3. 额外注意事项

  • 确保chromedriver.exe和GoogleChromePortable_114.0.5735.91文件夹确实与生成的EXE文件在同一目录下。
  • 无论使用PyInstaller的--onefile还是--onedir参数打包,上述代码都能正常适配,只要文件位置正确即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:02:24