Я пытаюсь прочитать консоль Chrome, используя Selenium Webdriver в node.js, но пока это не увенчалось успехом. Ошибок нет. Но все это возвращает пустой массив [].
Ниже приведен фрагмент функции 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();
Я уверен, что проблема проста, возможно, проблема с конфигурацией. Я просто не могу понять, в чем проблема. Я даже прибегал к чтению исходного кода webdriver в Git, чтобы увидеть, могу ли я что-нибудь увидеть, но безрезультатно.
Насколько я могу судить, получение содержимого консоли из Chrome с помощью webdriver - это не выход.
В итоге я решил проблему таким образом:
//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'));