Python代码中executable_path与options报错及打包exe失败问题咨询
代码错误分析与修正
你的代码存在三个核心问题,导致字段标红和打包exe出错:
executable_path参数已被废弃:Selenium 4.x及以上版本移除了该参数,不再支持通过这种方式指定Chrome驱动路径,必须改用Service类来传递驱动路径。- 路径转义错误:Python字符串中
\d会被解析为转义字符(匹配十进制数字的正则符号),导致实际路径无法正确识别。 - 固定路径不适合打包exe:硬编码的本地路径在exe打包后会失效,因为exe运行时的工作目录和开发环境不一致。
修正方案
方案1:手动指定驱动路径(适配Selenium 4.x)
先导入Service类,再修正初始化代码:
from selenium.webdriver.chrome.service import Service from selenium import webdriver # 用原始字符串(前缀r)避免转义问题 self.driver = webdriver.Chrome(service=Service(r"D:\driver\chromedriver.exe"), options=chrome_options)
方案2:自动管理驱动(推荐,适配打包场景)
使用webdriver-manager库自动下载、匹配对应版本的Chrome驱动,无需手动指定路径,打包更省心:
- 先安装依赖:
pip install webdriver-manager
- 修改代码:
from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
打包exe的注意事项
如果用方案2,打包时需要给PyInstaller添加必要的隐藏导入参数,确保依赖被正确打包:
pyinstaller --onefile --hidden-import=webdriver_manager --hidden-import=selenium your_script.py
内容的提问来源于stack exchange,提问作者Ammar alghareeb
相关产品推荐
相关产品推荐

