简体   繁体   中英

Writing DOM elements to the browser console in Nightmare

I'm using NightmareJS for headless browsing. 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 . However, console.log does not seem to work inside the .evaluate block.

How do I log stuff inside .evaluate to the console?

So I was able to solve this earlier using 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 . You can also use other Javascript Promises implementations besides the one I used here.

Hope it helps.

console.log() works fine inside of the page context (inside of evaluate() ), but you have to listen to it:

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. It would be too much. You have to print a representation of the DOM node which you have to build yourself.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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