Nightmare Js Rate Page

I run the following code using Nightmare.js:

var test = new Nightmare() .viewport(1000, 1000) .useragent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36") .goto('https://en.wikipedia.org/wiki/Ubuntu') .inject('js', 'jquery.js') .wait(500) .screenshot('page.png') .evaluate( function () { return $('h1.firstHeading').text(); //Get Heading }, function (value) { console.log("Not in page context"); } ) .run( function (err, nightmare) { if (err) return console.log(err); console.log('Done!'); } ); 

The page loads and the screenshot, page.png, is executed correctly, but the callback method will never be executed, as the message "Not in the context of the page" is never printed. Jquery.js is located in the same folder as the script, and it is successfully entered, because if I remove the jS injection I will get an error indicating that $ is undefined. I want to get the text content of the h1.firstHeading selector.

Why evaluation callback fails.

+5
source share
1 answer

The main problem is that console.log does not work in evaluate() .

evaluation is only responsible for returning data in the callback.

Currently, the evaluation function follows the .evaluate(fn, args1, args2) format .evaluate(fn, args1, args2) . Therefore, in your case, when your first function returns data, the next one will not.

If you want the header to simply return a value from the function and execute console.log (a nightmare) inside the launch function.

The following are sample code below:

 .evaluate( function () { if($('h1.firstHeading').text()) return $('h1.firstHeading').text(); //Get Heading else return "Not in page context"; } ) .run( function (err, nightmare) { if (err) return console.log(err); console.log(nightmare); console.log('Done!'); } ); 

Hope this helps.! Thanks

+7
source

Source: https://habr.com/ru/post/1235734/


All Articles