1

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(); 

問題はおそらく設定に問題があります。私は問題が何であるか把握できません。私はGitのwebdriverソースコードを読んで、何かを見ることができるかどうかを知ることにしましたが、無駄にしていました。

答えて

0

私が知る限り、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')); 
関連する問題