硒隐藏 chromedriver 控制台 window

selenium hide chromdriver console window

我用 python 创建了一个使用 selenium 的程序。我还使用 pyinstaller 创建了一个 .exe。如果我 运行 .exe chrome 正常打开。但由于某种原因,控制台也出现了。只有在我启动 .exe 时才会发生这种情况。如果我在 VS Code 中启动代码,只会出现 chrome window。

我发现了一些用 C# 编写的东西:

var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;

var driver = new ChromeDriver(driverService, new ChromeOptions());

我的 chromdriver 设置:

option = webdriver.ChromeOptions()
option.add_argument("--incogneto")
chromedriver_path = driverPath
browser = webdriver.Chrome(chromedriver_path)
browser.set_window_size(1100, 800)
browser.get("myurl")

如何在 Python 中执行此操作?

当您 运行 pyinstaller 命令时,尝试将其链接到此:pyinstaller ./main.py --onefile --noconsole --add-binary "chromedriver path;./driver"

--onefile‖输出为一个.exe.

--noconsole‖创建的exe执行时不显示控制台

--add-binary‖指定要添加到exe中的二进制文件。指定方法为"source_file_path; destination_file_path"。在这种情况下,我们要添加 chromedriver 文件。

当使用--onefile选项时,用--add-binary指定的二进制文件包含在exe中。它们在 运行 时被扩展到一个临时文件夹。因此,在 Python 源中使用相对路径可能不起作用。

例如需要使用相对路径的部分改写如下:

driver = webdriver.Chrome('./driver/chromedriver.exe')

改写如下:

import os
import sys

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.dirname(__file__)
    return os.path.join(base_path, relative_path)

driver = webdriver.Chrome(resource_path('./driver/chromedriver.exe'))

添加函数resource_path即可使用。 resource_path获取路径的逻辑如下:

从exe执行时,从sys._MEIPASS获取相对路径(从exe执行时,输入临时文件夹路径)

从Python执行时,从该文件(文件)获取相对路径。 现在,无论您 运行 来自 Python 还是 exe 文件,它都可以正常工作。

如果 NONE 可行,请在您的代码中尝试:

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

chrome_service = ChromeService('chromedriver')
chrome_service.creationflags = CREATE_NO_WINDOW # We change the property in Service class, default was 0
driver = webdriver.Chrome(service=chrome_service)

以上代码仅适用于 selenium 版本 4.0.0 或更高版本。如果你没有这个版本,试试这个 pip 命令:pip install selenium=4.0.0a7

然后,程序运行,但是 chromedriver window 没有出现!

Selenium4 发布了这个功能!无需编辑库代码。

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')
chrome_service.creationflags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)

使用 pip install selenium 更新或升级软件包 pip install selenium --upgrade