在 python 中隐藏 chromeDriver 控制台

新手上路,请多包涵

我在 Selenium 中使用 chrome 驱动程序打开 chrome,登录路由器,按一些按钮,上传配置等。所有代码都是用 Python 编写的。

这是获取驱动程序的代码部分:

 chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory":  self.user_local}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.experimental_options.
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)

return driver

当我启动我的应用程序时,我得到一个 chromedriver.exe 控制台(一个黑色窗口),然后打开一个 chrome 窗口,我的所有请求都已完成。

我的问题:python 中是否有隐藏控制台窗口的方法?

(正如你所看到的,我也在重新调整 chrome 窗口的大小,我的偏好是以用户不会注意到屏幕上发生的任何事情的方式做事)

谢谢 Sivan

原文由 sivan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 975
1 个回答

您将必须编辑 Selenium 源代码才能实现此目的。我也是菜鸟,我不完全理解编辑源代码的总体后果,但这是我在 Windows 7、Python 2.7 上实现隐藏 webdriver 控制台窗口所做的工作。

找到并编辑此文件,如下所示:位于 Python 文件夹中的 Lib\site-packages\selenium\webdriver\common\service.py

通过以这种方式添加创建标志来编辑 Start() 函数: creationflags=CREATE_NO_WINDOW

编辑后的方法如下:

 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())
        self.process = subprocess.Popen(cmd, env=self.env,
                                        close_fds=platform.system() != 'Windows',
                                        stdout=self.log_file, stderr=self.log_file, creationflags=CREATE_NO_WINDOW)
    except TypeError:
        raise

您将必须添加相关的导入:

 from win32process import CREATE_NO_WINDOW

这也适用于 Chrome webdriver,因为它们导入相同的文件以启动 webdriver 进程。

原文由 Chanticleer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题