在python中隐藏chromeDriver控制台

siv*_*van 4 python selenium selenium-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
Run Code Online (Sandbox Code Playgroud)

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

我的问题:在python中有一种隐藏控制台窗口的方法吗?

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

谢谢Sivan

Ali*_*jad 20

新的简单解决方案!(在硒4中)

我也需要这个,所以我在 GitHub 上实现并提交了这个功能,作为selenium4版本的一部分。我们不再需要为此编辑selenium 库。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows

# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
# Use `chrome_service.creationflags` for selenium < 4.6
chrome_service.creation_flags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)
Run Code Online (Sandbox Code Playgroud)

现在,命令提示符窗口无法打开。当您有一个负责打开 selenium 浏览器的 GUI 桌面应用程序时,这尤其有用。

另请注意,我们只需要在 Windows 中执行此操作。

  • 在某些时候,selenium 将creationflags 更改为creation_flags。进行此更改后,该解决方案对我有用 (5认同)
  • @AliSajjad 请注意,自 4.6.0 版本以来,Selenium 已将其 Service.creationflags 转变为 Service.creation_flags。 (3认同)

Cha*_*eer 12

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

按如下所示找到并编辑此文件:位于Python文件夹中的 Lib\site-packages\selenium\webdriver\common\services.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
Run Code Online (Sandbox Code Playgroud)

您必须添加相关导入:

from win32process import CREATE_NO_WINDOW
Run Code Online (Sandbox Code Playgroud)

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

  • 值得注意的是`CREATE_NO_WINDOW` [只是一个常量](https://github.com/mhammond/pywin32/blob/7da19cd2ca3fac06638d9af690b8b6f5fcc65e8b/win32/Lib/win32con.py#L454032),所以你不一定需要。常量的值是“134217728”,它应该是一样的。 (3认同)
  • 你好,我使用的是 Windows 10、Python 3.7 和 Selenium 3.14,我尝试使用该函数,因为我在 Windows 10 上,它给了我“from win32process import CREATE_NO_WINDOW”的导入错误。因此,我按照上面的建议使用了常量 134217728。我的 Popen 参数中有 stdin = 'PIP'。我把它去掉了。现在,当我在本地运行时,脚本工作正常。但是当我使用 pyinstaller 生成 .exe 时,它​​根本不运行。任何解决方案。 (2认同)

Nei*_*ski 5

与此相关的问题很多,答案也很多。问题在于,在没有自己的控制台窗口的Python进程中使用Selenium 会导致其chromedriver在新窗口中启动其驱动程序(包括)。

您不必选择直接修改Selenium代码(尽管最终需要这样做),而是要为Chrome WebDriver及其Service使用的类创建自己的子类。该Service班是其中硒实际调用Popen启动服务过程中,如chromedriver.exe(如接受的回答中提到):

import errno
import os
import platform
import subprocess
import sys
import time
import warnings

from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from selenium.webdriver.chrome import service, webdriver, remote_connection

class HiddenChromeService(service.Service):

    def start(self):
        try:
            cmd = [self.path]
            cmd.extend(self.command_line_args())

            if platform.system() == 'Windows':
                info = subprocess.STARTUPINFO()
                info.dwFlags = subprocess.STARTF_USESHOWWINDOW
                info.wShowWindow = 0  # SW_HIDE (6 == SW_MINIMIZE)
            else:
                info = None

            self.process = subprocess.Popen(
                cmd, env=self.env,
                close_fds=platform.system() != 'Windows',
                startupinfo=info,
                stdout=self.log_file,
                stderr=self.log_file,
                stdin=subprocess.PIPE)
        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(
                "Executable %s must be in 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't connect to the Service %s" % (
                    self.path,))


class HiddenChromeWebDriver(webdriver.WebDriver):
    def __init__(self, executable_path="chromedriver", port=0,
                options=None, service_args=None,
                desired_capabilities=None, service_log_path=None,
                chrome_options=None, keep_alive=True):
        if chrome_options:
            warnings.warn('use options instead of chrome_options',
                        DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())

        self.service = HiddenChromeService(
            executable_path,
            port=port,
            service_args=service_args,
            log_path=service_log_path)
        self.service.start()

        try:
            RemoteWebDriver.__init__(
                self,
                command_executor=remote_connection.ChromeRemoteConnection(
                    remote_server_addr=self.service.service_url,
                    keep_alive=keep_alive),
                desired_capabilities=desired_capabilities)
        except Exception:
            self.quit()
            raise
        self._is_remote = False
Run Code Online (Sandbox Code Playgroud)

I removed some of the extra comments and doc string goo for brevity. You would then use this custom WebDriver the same way you'd use the official Chrome one in Selenium:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
headless_chrome = HiddenChromeWebDriver(chrome_options=options)

headless_chrome.get('http://www.example.com/')

headless_chrome.quit()
Run Code Online (Sandbox Code Playgroud)

Finally, if creating a custom WebDriver is not for you and you don't mind a window flickering and disappearing then you can also use the win32gui library to hide the window after starting up:

# hide chromedriver console on Windows
def enumWindowFunc(hwnd, windowList):
    """ win32gui.EnumWindows() callback """
    text = win32gui.GetWindowText(hwnd)
    className = win32gui.GetClassName(hwnd)
    if 'chromedriver' in text.lower() or 'chromedriver' in className.lower():
        win32gui.ShowWindow(hwnd, False)
win32gui.EnumWindows(enumWindowFunc, [])
Run Code Online (Sandbox Code Playgroud)


小智 2

启动 Chrome 浏览器时,没有看到带有给定示例代码的 chromedriver 控制台。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options 
from time import sleep
options = webdriver.ChromeOptions()
prefs = {"download.default_directory":  r"C:\New_Download"}
options.add_experimental_option("prefs", prefs)
print(options.experimental_options)

chromeDriverPath = r'C:\drivers\chromedriver.exe'
driver = webdriver.Chrome(chromeDriverPath,chrome_options=options)
driver.get("http://google.com")
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)
Run Code Online (Sandbox Code Playgroud)

  • 当您在没有控制台窗口的进程中使用 Selenium 时,会显示控制台窗口。在控制台窗口中运行 Selenium 代码不会有任何新的弹出控制台,因为它已经附加了一个控制台。 (3认同)