selenium+python 去除启动的黑色cmd窗口方法
其实selenium启动窗口的时候就是使用了subprocess.Popen启动的驱动程序的,只要在启动的时候加上启动不显示窗口的参数即可。
下面魔改开始O(∩_∩)O哈哈~
修改代码位于D:\Python35\Lib\site-packages\selenium\webdriver\common\service.py主要是Service类的start函数
defstart(self):
"""
StartstheService.
:Exceptions:
-WebDriverException:Raisedeitherwhenitcan'tstarttheservice
orwhenitcan'tconnecttotheservice
"""
try:
cmd=[self.path]
cmd.extend(self.command_line_args())
if'win32'instr(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窗口进程
exceptTypeError:
raise
exceptOSErroraserr:
iferr.errno==errno.ENOENT:
raiseWebDriverException(
"'%s'executableneedstobeinPATH.%s"%(
os.path.basename(self.path),self.start_error_message)
)
eliferr.errno==errno.EACCES:
raiseWebDriverException(
"'%s'executablemayhavewrongpermissions.%s"%(
os.path.basename(self.path),self.start_error_message)
)
else:
raise
exceptExceptionase:
raiseWebDriverException(
"Theexecutable%sneedstobeavailableinthepath.%s\n%s"%
(os.path.basename(self.path),self.start_error_message,str(e)))
count=0
whileTrue:
self.assert_process_still_running()
ifself.is_connectable():
break
count+=1
time.sleep(1)
ifcount==30:
raiseWebDriverException("CannotconnecttotheService%s"%self.path)
注意在前面先导入sys包
因为隐藏了驱动cmd窗口所以结束程序的时候一定要做杀死驱动cmd窗口的动作哦!O(∩_∩)O!!
以上这篇selenium+python去除启动的黑色cmd窗口方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。