如何禁用Selenium与Chrome Driver的日志输出
禁用ChromeDriver与Selenium启动日志及CDP版本匹配通知的方法
Python 实现方式
- 屏蔽ChromeDriver启动日志:用
ChromeService把日志路径指向空设备(Linux/macOS填/dev/null,Windows填NUL),同时把Selenium的日志级别调到最高,只保留致命错误。
示例代码:from selenium import webdriver from selenium.webdriver.chrome.service import Service import logging # 让Selenium只输出致命错误日志 logging.getLogger('selenium').setLevel(logging.CRITICAL) # 配置ChromeDriver服务,把日志丢进空设备 service = Service(executable_path='chromedriver', log_path='/dev/null') # Windows系统替换成'NUL' options = webdriver.ChromeOptions() # 额外禁用Chrome自身的日志输出 options.add_argument('--log-level=3') options.add_argument('--silent') # 屏蔽CDP版本不匹配的通知 options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome(service=service, options=options)
Java 实现方式
- 关闭ChromeDriver启动日志:通过
ChromeDriverService指定日志文件为空设备,同时配置ChromeOptions屏蔽各类日志和警告。
示例代码:import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import java.util.Map; public class DisableChromeLogs { public static void main(String[] args) { // 配置ChromeDriver服务,将日志输出到空设备 ChromeDriverService service = new ChromeDriverService.Builder() .withLogFile(new java.io.File("/dev/null")) // Windows系统替换成"NUL" .build(); ChromeOptions options = new ChromeOptions(); // 禁用Chrome的日志输出 options.addArguments("--log-level=3"); options.addArguments("--silent"); // 屏蔽CDP版本匹配警告及其他驱动日志 options.setCapability("goog:loggingPrefs", Map.of("browser", "OFF", "driver", "OFF")); ChromeDriver driver = new ChromeDriver(service, options); } }
命令行直接启动ChromeDriver的方式
如果不通过代码调用,直接从命令行启动ChromeDriver,可以加--silent参数屏蔽启动日志,或者把日志重定向到空设备:
# Linux/macOS下屏蔽所有日志 chromedriver --silent > /dev/null 2>&1 # Windows下屏蔽所有日志 chromedriver --silent > NUL 2>&1
内容的提问来源于stack exchange,提问作者muell
相关产品推荐
相关产品推荐

