我试图浏览在线词典的页面。这是我的代码:
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });
var links = [];
function goToLink(linkName){
nightmare
.goto(linkName)
.evaluate( () => {
var href = document.querySelector("span.next a").href;
links.push(href)
return href;
})
.then((href) => {
goToLink(href);
})
.catch((error) => {
console.error('Error:', error);
});
}
goToLink("http://lexicon.quranic-research.net/data/01_a/000_!.html");
我得到了Error: links is not defined
。链接在var links = [];
处明确定义,但内部功能并未了解它。这是怎么回事?
答案 0 :(得分:1)
问题是evaluate
回调是在不同的上下文中调用的,并没有看到links
。你可以尝试做的就是这样传递:
(...)
.evaluate( links => {
var href = document.querySelector("span.next a").href;
links.push(href)
return href;
}, links)
(...)
links
是回调的参数。您必须将其作为evaluate
函数中的第二个参数传递。