PyInstaller打包Selenium爬虫后文件下载路径异常问题求助
解决PyInstaller打包Selenium爬虫后PDF下载路径丢失问题
问题原因
PyInstaller单文件打包时,sys._MEIPASS指向程序运行时临时解压的目录,程序退出后该目录会被自动删除。原代码将下载目录设在此处,导致下载的PDF文件随临时目录被清理,无法留存。
解决方案
将下载目录改为exe文件所在的真实目录,同时修正配置文件的读取路径,确保打包后能正确访问资源文件。
修改后的代码示例
import sys import os from selenium import webdriver # 获取程序运行的基础路径 if getattr(sys, 'frozen', False): # 打包为exe时,取exe文件所在的目录 base_path = os.path.dirname(os.path.abspath(sys.executable)) else: # 未打包时,取当前脚本所在目录 base_path = os.path.abspath(".") # 创建下载目录(位于exe/脚本所在目录下的Files文件夹) download_dir = os.path.join(base_path, "Files") if not os.path.exists(download_dir): os.makedirs(download_dir) # 读取urls.txt文件(使用base_path拼接路径,确保打包后能找到文件) urls = [] with open(os.path.join(base_path, "test_urls.txt"), "r") as file: urls = [url.strip() for url in file.readlines()] # 配置Chrome浏览器下载参数 chrome_options = webdriver.ChromeOptions() prefs = { "download.default_directory": download_dir, "download.prompt_for_download": False, "directory_upgrade": True, "safebrowsing.enabled": True, "safebrowsing.disable_download_protection": True, "profile.default_content_setting_values.automatic_downloads": 1, "profile.default_content_settings.popups": 0, "profile.content_settings.exceptions.automatic_downloads.*.setting": 1 } chrome_options.add_experimental_option("prefs", prefs) # 初始化Chrome驱动 driver = webdriver.Chrome(options=chrome_options)
正确的打包命令
打包时需将test_urls.txt和chromedriver.exe(或对应系统的chromedriver)添加到打包资源中:
# Windows系统 pyinstaller --onefile --add-data "test_urls.txt;." --add-data "chromedriver.exe;." main.py # macOS/Linux系统 pyinstaller --onefile --add-data "test_urls.txt:." --add-data "chromedriver:." main.py
效果说明
修改后,PDF文件会直接保存到exe文件所在目录的Files文件夹中,程序退出后文件不会被删除,同时test_urls.txt也能被正确读取。
内容的提问来源于stack exchange,提问作者Hao Yuan
相关产品推荐
相关产品推荐

