繁体   English   中英

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

[英]Writing DOM elements to the browser console in Nightmare

我正在使用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.evaluate块中似乎不起作用。

如何将.evaluate内部的内容记录到控制台?

因此,我能够使用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之前的Nightmare版本,因为从2.x版开始,Electron被用作基础浏览器,而不是PhantomJS。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM