python - Python:如何在 Selenium 中隐藏输出的 Chrome 消息?
问题描述
我想做的事:
我想使用 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正在监听...”
我试图解决这个问题:
使用上下文库
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')
使用日志级别=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 正在监听...”?
解决方案
答案是:
基于 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,selenium 3.141.0)
请感谢我花费数小时搜索答案。