我正尝试在一个迷你网络爬虫中使用selenium来获取页面源代码。我的输出日志被selenium日志入侵了,有没有办法完全禁用日志记录,或者只是以某种方式将其重定向到/dev/null?
日志记录消息如下:
Starting ChromeDriver 2.43.600233
(523efee95e3d68b8719b3a1c83051aa63aa6b10d) on port 1628
Only local connections are allowed.
ott 24, 2018 7:52:01 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMAZIONI: Detected dialect: OSS
我将通过以下方式调用驱动程序:
WebDriver driver = null;
try {
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("/usr/bin/chromium");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--silent");
chromeOptions.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
driver = new ChromeDriver(chromeOptions);
/*FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
System.setProperty("webdriver.gecko.driver", "/usr/local/bin/geckodriver");
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "true");
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "/dev/null");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);*/
if(driver!=null) {
driver.get(link);
发布于 2019-01-22 12:36:56
醉猫的答案是正确的,而且非常有用,可以在日志中删除100条毫无意义的信息。也许可以使用java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.SEVERE);
捕获错误(使用Level.SEVERE而不是Level.OFF)
Chromedriver v83 (2020年更新)
请注意,设置属性的替代方法是:
System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");
是这样的:
DriverService.Builder serviceBuilder = new ChromeDriverService.Builder().withSilent(true);
ChromeOptions options = new ChromeOptions();
// ... addArguments to options ....
ChromeDriverService chromeDriverService = (ChromeDriverService)serviceBuilder.build();
ChromeDriver driver = new ChromeDriver(chromeDriverService, options);
然而,无论出于什么原因,在Chromedriver v83上,.withSilent(true)
或设置属性都不起作用(在Linux和Windows上得到确认)。我需要添加一行代码来重定向输出:
:
ChromeDriverService chromeDriverService = (ChromeDriverService)serviceBuilder.build();
chromeDriverService.sendOutputTo(new FileOutputStream("/dev/null"));
ChromeDriver driver = new ChromeDriver(chromeDriverService, options);
如果你愿意,你可以用一个真实的文件替换"/dev/nul“(用于调试等)。或者是一种与平台无关的处理空输出的方法,它可以与Java 8+一起使用:
chromeDriverService.sendOutputTo(new OutputStream(){@Override public void write(int b){}});
我猜测这可能是v83版本中的一个错误,但至少它让我找到了另一种重定向或关闭chromedriver日志记录的方法。
https://stackoverflow.com/questions/52975287
复制相似问题