无法使用Node.js中的Selenium Webdriver检索Chrome控制台的内容

我正在尝试使用node.js中的Selenium Webdriver来阅读Chrome控制台,但是到目前为止它并不成功。 没有错误。 但是它返回的是一个空数组[]。

以下是HTML和JavaScript函数的一个片段。 当在Chrome中手动运行时,这些写入控制台就好了。

<button name="button1" type="button" onclick="test_console()">Test</button> function test_console() { console.log("Hello World"); } 

以下是我在node.js中使用的代码来尝试将输出传递给Chrome。

 const webdriver = require('selenium-webdriver'); const chromeDriver = require('selenium-webdriver/chrome'); const logging = require('selenium-webdriver').logging; const path = require('chromeDriver').path; const service = new chromeDriver.ServiceBuilder(path).build(); chromeDriver.setDefaultService(service); const {By, Key} = webdriver; webdriver.promise.USE_PROMISE_MANAGER = false; const CHROME_BIN_PATH = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'; const prefs = new logging.Preferences(); prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); const options = new chromeDriver.Options(); options.setChromeBinaryPath(CHROME_BIN_PATH); options.addArguments( 'headless', 'disable-gpu', 'verbose', 'disable-impl-side-painting', ); const main = async () => { try { const driver = await new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .setLoggingPrefs(prefs) .forBrowser('chrome') .setChromeOptions(options) .build(); await driver.get('http://example.com/example.html'); //clicking this button manually in Chrome writes to the console await driver.findElement(By.name('button1')).click(); await driver.manage().logs().get(logging.Type.BROWSER) .then(function(entries) { console.log(entries); }); await driver.close(); await driver.quit(); } catch (error) { await driver.close(); await driver.quit(); console.log(error); } }; main(); 

我确定这个问题很简单,可能是一个configuration问题。 我只是不知道问题可能是什么。 我甚至使用Git中的webdriver源代码来看看我能否看到任何东西,但无济于事。

据我所知,使用webdriver从Chrome获取控制台的内容是不行的。

我最终以这种方式解决了这个问题:

 //append a div to the body of the page await driver.executeScript("var div = document.createElement('div'); div.id = 'console_log'; document.body.appendChild(div);"); //override console.log to write the log message to the new div await driver.executeScript("console.log = function(message){document.getElementById('console_log').innerHTML += message}"); //get the contents of the new div const console_log = await driver.findElement(By.id('console_log')); console.log(await console_log.getAttribute('innerHTML'));