其實 selenium啟動窗口的時候就是 使用了subprocess.Popen 啟動的驅動程序的,只要在啟動的時候加上啟動不顯示窗口的參數即可。
下面魔改開始O(∩_∩)O哈哈~
修改代碼 位于 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窗口 所以 結束程序的時候 一定要做殺死驅動cmd窗口的動作哦 !O(∩_∩)O!!
以上這篇selenium+python 去除啟動的黑色cmd窗口方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答