Python Selenium 隐藏启动时黑色 CMD 窗口的方法
本文介绍如何通过修改 Selenium 源码中的 Service 类 start 函数,利用 subprocess.STARTUPINFO 参数在 Windows 平台下隐藏浏览器驱动启动时弹出的黑色 CMD 窗口,并强调需在程序结束时手动杀死驱动进程以避免残留。
Selenium 启动浏览器驱动时,底层实际上是调用了 subprocess.Popen 来创建进程。要实现启动时不显示黑色控制台窗口,只需在启动参数中进行相应配置即可。
接下来介绍具体的代码修改步骤。
需要修改的代码文件位于 D:\Python35\Lib\site-packages\selenium\webdriver\common\service.py,主要涉及 Service 类的 start 函数。
def start(self):
"""
Starts the Service.
:Exceptions:
- WebDriverException : Raised either when it can't start the service
or when it can't connect to the service
"""
try:
cmd = [self.path]
cmd.extend(self.command_line_args())
if 'win32' in str(sys.platform).lower(): ### 这里判断是否是windows平台
### 在windows平台上就隐藏窗口
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
else:
startupinfo = None
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file, stderr=self.log_file,startupinfo=startupinfo) ### 启动驱动
self.PID = self.process.pid ### 将cmd窗口的进程pid 保留 因为 窗口被隐藏了 所以在后续程序中必须考虑主控进程结束的时候必须结束掉 驱动cmd窗口进程
except TypeError:
raise
except OSError as err:
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), self.start_error_message)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), self.start_error_message)
)
else:
raise
except Exception as e:
raise WebDriverException(
"The executable %s needs to be available in the path. %s\n%s" %
(os.path.basename(self.path), self.start_error_message, str(e)))
count = 0
while True:
self.assert_process_still_running()
if self.is_connectable():
break
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to the Service %s" % self.path)
在修改前,请确保已导入 sys 模块。
由于驱动程序的 CMD 窗口已被隐藏,因此在主程序结束运行时,必须显式执行杀死驱动进程的操作,否则驱动进程可能会在后台残留。
以上是关于使用 Python 和 Selenium 去除启动时黑色 CMD 窗口的完整方法,供参考使用。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









