selenium+python 去除启动的黑色cmd窗口方法

yipeiwu_com5年前Python基础

其实 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窗口方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pycharm安装和首次使用教程

pycharm安装和首次使用教程

PyCharm 是我用过的python编辑器中,比较顺手的一个。而且可以跨平台,在macos和windows下面都可以用,这点比较好。是python现在最好用的编辑器,没有之一。 首先预...

python算法题 链表反转详解

python算法题 链表反转详解

链表的反转是一个很常见、很基础的数据结构题,输入一个单向链表,输出逆序反转后的链表,如图:上面的链表转换成下面的链表。实现链表反转有两种方式,一种是循环迭代,另外一种方式是递归。 第...

Python多进程写入同一文件的方法

Python多进程写入同一文件的方法

最近用python的正则表达式处理了一些文本数据,需要把结果写到文件里面,但是由于文件比较大,所以运行起来花费的时间很长。但是打开任务管理器发现CPU只占用了25%,上网找了一下原因发现...

python 不同方式读取文件速度不同的实例

1、按行读取较慢较耗时: srcFiles = open('inputFile.txt', 'r') for file_path in srcFiles: file_path...

Python+Django搭建自己的blog网站

Python+Django搭建自己的blog网站

一、前言 1.1.环境 python版本:3.6 Django版本:1.11.6 1.2.预览效果 最终搭建的blog的样子,基本上满足需求了。框架搭好了,至于CSS,可以根据自己喜好随...