简体   繁体   English

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

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

I'm using NightmareJS for headless browsing. 我正在使用NightmareJS进行无头浏览。 My code looks like this: 我的代码如下所示:

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!');
    });

I need to debug DOM elements often using console.log . 我需要经常使用console.log调试DOM元素。 However, console.log does not seem to work inside the .evaluate block. 但是, console.log.evaluate块中似乎不起作用。

How do I log stuff inside .evaluate to the console? 如何将.evaluate内部的内容记录到控制台?

So I was able to solve this earlier using Promises. 因此,我能够使用Promises来解决此问题。 Here's the updated code: 这是更新的代码:

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

Remember to npm install es6-promise . 记住要npm install es6-promise You can also use other Javascript Promises implementations besides the one I used here. 除了我在这里使用的实现之外,还可以使用其他Javascript Promises实现。

Hope it helps. 希望能帮助到你。

console.log() works fine inside of the page context (inside of evaluate() ), but you have to listen to it: 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(){})
    ...

Keep in mind that you can't just fully output DOM nodes to the console like you would in the developer tools of your favorite browser. 请记住,您不能像在您喜欢的浏览器的开发人员工具中那样,将DOM节点完全输出到控制台。 It would be too much. 太过分了。 You have to print a representation of the DOM node which you have to build yourself. 您必须打印自己要构建的DOM节点的表示

You can also use all other events that PhantomJS provides in the same way, but this only works for Nightmare versions prior to 2.x, because from version 2.x onward Electron is used as the underlying browser and not PhantomJS. 您还可以以相同的方式使用PhantomJS提供的所有其他事件,但这仅适用于2.x之前的Nightmare版本,因为从2.x版开始,Electron被用作基础浏览器,而不是PhantomJS。

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

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