我想在运行nightmare.js之后获取gig中的所有数据,但我一直没有定义演出
const Nightmare = require('nightmare');
const nightmare = Nightmare({show: true});
nightmare
.goto('https://www.nairaland.com/romance')
.wait(1000)
.evaluate(function(){
var gig = [];
var links = document.querySelectorAll('a');
links.forEach(function(result){
gig.push(result.innerHTML)
})
return gig;
})
.end()
.then(function(result){
gig.forEach(function(result){
console.log(gig)
})
})
.catch(error => {
console.error('The Error is', error)
})
您对gig = []
的声明属于评估函数的范围。当该函数返回时,它超出范围。
把它放在外部范围内。也许是这样的?
const gig = [];
nightmare
.goto('https://www.nairaland.com/romance')
.wait(1000)
.evaluate(function(){
const links = document.querySelectorAll('a');
links.forEach(function(result){
...
您在传递给gig
的函数范围内声明了变量evaluate()
。该变量对于声明它的函数中的代码是可见的,包括在同一作用域中定义的其他嵌套函数,但对于存在于函数作用域外的代码不可见。
要解决此问题,请在调用var gig=[];
之前声明变量nightmare.goto(...
。
这会将变量放在外部作用域中,使其对所有更深层嵌套的函数可见。将功能视为单向镜面玻璃。您可以看到该函数,查看外部世界中的变量,但外部世界无法看到您的函数来查看其内部变量。