在Nightmare中将DOM元素写入浏览器控制台

Writing DOM elements to the browser console in Nightmare

本文关键字:浏览器 控制台 元素 Nightmare 中将 DOM      更新时间:2023-09-26

我使用NightmareJS进行无头浏览。我的代码如下:

var Nightmare = require('nightmare');
var google = new Nightmare()
    .goto('http://www.google.com')
    .wait(3000)
    .inject('js', 'jquery.min.js')
    .screenshot('screenshot.png')
    .evaluate(function(){
        return $('#footer').html();
    }, function(value){
        console.log(value);
    })
    .run(function(err){
        console.log('All done!');
    });

我需要经常使用console.log调试DOM元素。然而,console.log似乎在.eevaluate块内不起作用。

如何将内部的内容记录到控制台。评估

所以我早些时候使用Promises解决了这个问题。这是更新后的代码:

var Nightmare = require('nightmare');
var Promise = require('es6-promise').Promise;
var nightmare = new Nightmare();
Promise.resolve(nightmare
    .goto('http://www.google.com')
    .wait(3000)
    .inject('js', 'jquery.min.js')
    .screenshot('screenshot.png')
    .evaluate(function(){
        return $('#footer').html();
    }))
    .then(function(value){
        console.log(value);
        console.log('All Done!');
        return nightmare.end();
    })
    .then(function(result){
    }, function(err){
        console.error(err);
    });

记住npm install es6-promise。除了我在这里使用的实现之外,您还可以使用其他Javascript Promises实现。

希望能有所帮助。

console.log()在页面上下文中(在evaluate()中)工作良好,但您必须听它:

new Nightmare()
    .on("consoleMessage", function(msg){
        console.log("remote> " + msg);
    })
    .goto('http://www.google.com')
    .evaluate(function(){
        console.log($('#footer').html());
    }, function(){})
    ...

请记住,您不能像在您喜欢的浏览器的开发工具中那样,将DOM节点完全输出到控制台。这太过分了。您必须打印DOM节点的表示,您必须自己构建它。

您也可以以相同的方式使用PhantomJS提供的所有其他事件,但这只适用于2.x之前的噩梦版本,因为从2.x版本开始,Electron被用作底层浏览器,而不是PhantomJS。