解决PyInstaller打包selenium脚本时弹出driver终端窗口
- 找到service.py
C:\Users\XXX\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\common\service.py - 添加creationflags
在第77行添加:
creationflags=134217728 - 使用PyInstaller打包
pyinstaller -F -w -i xxx.ico xxx.py
有的解决方法是修改 …/Lib/sit-packages/selenium/webdriver/common/service.py 里的 creationflags=134217728,但selenium 版本升级了,这种方法不行。因为其他人的python 和 selenium 版本跟我的不一样,导致不能照搬但思路可以参考。我的python 版本是Python 3.10.10 ,selenium 4.8.2
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
class MyService(Service):
def __init__(self, executable_path: str,
port: int = 0, service_args=None,
log_path: str = None, env: dict = None):
super(Service, self).__init__(
executable_path,
port,
service_args,
log_path,
env,
"Please see https://chromedriver.chromium.org/home")
# self.creationflags = 134217728
self.creation_flags = 134217728
然后在新建driver 时 webdriver.Chrome 添加参数 service,把自定义的Service 类MyService(…) 传入 ,
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_experimental_option("excludeSwitches", ['enable-logging'])
driver = webdriver.Chrome(chrome_options=chrome_options,
service=MyService(ChromeDriverManager().install()))
已经有博主通过实现自己的类让窗口不再弹出,借鉴他的思路,因为项目可以直接提供python环境,所以我选择了直接修改源码的代码实现。
# 在service.py的60行开始添加几行代码,修改启动参数
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
si.wShowWindow = subprocess.SW_HIDE
import subprocess
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()
if __name__ == "__main__":
# test with "pythonw.exe"
launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])