【问题标题】:Hide command prompt in Selenium ChromeDriver在 Selenium ChromeDriver 中隐藏命令提示符
【发布时间】:2018-02-07 01:07:16
【问题描述】:
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;

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

是否有可能在 Python 中实现这一点?我已经尝试了 StackoverFlow 和外部发布的所有可能的修复,但是当我运行我的 .exe 时没有任何修复,cmd 也会出现。

Python 3.6,最新的 Selenium 版本 (3.9)。

【问题讨论】:

标签: python selenium selenium-webdriver


【解决方案1】:

我找到了在 python 中复制上述代码的方法(或多或少) 用过这个fix 作为我灵感的基础。

经过几个小时的挣扎(以及非常糟糕的话),我在 github 上创建了这个commit,现在可以通过代码轻松更改控制台提示行为。 我将尝试在官方资源中提供它。希望它能让您节省时间和耐心。

第 1 步

找到service.py,一般在"X:\YourPythonFold\Lib\site-packages\selenium\webdriver\common\service.py"

第 2 步

替换这些行(n° 72-76 大约,低于 start 方法 def):

self.process = subprocess.Popen(cmd, env=self.env,
                                            close_fds=platform.system() != 'Windows',
                                            stdout=self.log_file,
                                            stderr=self.log_file,
                                            stdin=PIPE)

if any("hide_console" in arg for arg in self.command_line_args()):
                self.process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, creationflags=0x08000000)
            else:
                self.process = subprocess.Popen(cmd, env=self.env, close_fds=platform.system() != 'Windows', stdout=self.log_file, stderr=self.log_file, stdin=PIPE)

最后在您的代码中,当您设置驱动程序时(我选择 Chrome 作为示例):

args = ["hide_console", ]
driver = webdriver.Chrome("your-path-to-chromedriver.exe", service_args=args, ...)

编辑源代码时,注意PEP! 不要使用制表符,只使用空格!

【讨论】:

  • 我发现保留 close_fds=platform.system() != 'Windows' 参数可确保在关闭应用程序时始终关闭 IEDriverServer.exe 进程。这可能是首选,否则您最终会遇到多个不可见的进程。
【解决方案2】:

我找到了解决此问题的方法:不要使用 -w--Windowed pyinstaller 选项。换句话说,这样做:

pyinstaller --onefile "main.py"

不是这个:

pyinstaller --onefile -w "main.py"

是的,一开始你会得到一个命令窗口,但你不会在每次调用 geckodriver.exe 时都弹出这个窗口。我在 firefox 上苦苦挣扎,因此 geckodriver.exe

【讨论】:

    【解决方案3】:

    selenium4 发布以来,此功能已添加到python 库中!看到这个answer

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2022-11-23
      • 1970-01-01
      • 2012-11-13
      • 2014-02-04
      • 2020-09-06
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多