Python:如何在Selenium中隐藏Chrome输出消息?

时间:2018-11-19 10:21:23

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver

我想做什么:

我想使用Selenium ChromeDriver打开Chrome浏览器,而不会将Chrome消息输出到控制台。

我做了什么:

from selenium import webdriver
driver = webdriver.Chrome(r'C:\Users\u1\Documents\scripts\chromedriver.exe')

输出:

C:\Users\u1\Documents\scripts>python test.py

DevTools listening on ws://127.0.0.1:50605/devtools/browser/11c9063a-44ce-4b39-9566-9e6c6270025c

我想隐藏输出消息“ DevTools正在监听...”

我试图解决的问题:

使用contextlib

from selenium import webdriver
import contextlib

with contextlib.redirect_stdout(None):
   driver = webdriver.Chrome(r'C:\Users\u1\Documents\scripts\chromedriver.exe')

使用devnull

from selenium import webdriver
import subprocess

devnull = subprocess.DEVNULL
subprocess.Popen(open_browser(), stdout=devnull, stderr=devnull)
def open_browser():
    driver = webdriver.Chrome(r'C:\Users\u1\Documents\scripts\chromedriver.exe')

使用log-level = 3

chrome_options = Options()
chrome_options.add_argument("--log-level=3")
driver = webdriver.Chrome(r'C:\Users\u1\Documents\scripts\chromedriver.exe', chrome_options=chrome_options)

但是仍然显示该消息。如何在Python中隐藏输出消息“ DevTools正在监听...”?

3 个答案:

答案 0 :(得分:3)

将此选项添加到您的驱动程序中,您的问题将得到解决:

options = webdriver.ChromeOptions()<br>
options.add_experimental_option('excludeSwitches', ['enable-logging'])

答案 1 :(得分:0)

这些是Chrome消息,因此您需要设置Chrome日志级别的选项以隐藏这些消息,将日志级别设置为--log-level=3就足够了(仅致命日志消息。

from selenium.webdriver.chrome.options import Options
[...]
chrome-options = Options()
chrome-options.add_argument("--log-level=3")
driver = webdriver.Chrome(chrome_options=chrome-options)

也是出于好奇,请问为什么?

答案 2 :(得分:0)

DevTools listening on ws://127.0.0.1:57671/devtools/browser/8a586f7c-5f2c-4d10-8174-7a7bf50e49b5 with Selenium and Python中的类似问题。

答案是:

基于Chanticleer在python中隐藏chromeDriver控制台中

按以下步骤查找和编辑此文件:位于Python文件夹中的Lib \ site-packages \ selenium \ webdriver \ common \ services.py中。

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

from win32process import 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

非常适合我(python3.7,硒3.141.0)

请花点时间搜索答案,这是我的功劳。