如何使用NightmareJS进行多个查询?

下面的Javascript是打算使用NightmareJS来search一个网站的3个职位,并返回谁上传的职位的用户名。

var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); var inputArray = [198,199,201]; var runNext = function (i) { nightmare .goto('http://theshitpit.com/goto.php') .insert('form [name=postnum]', i) .click('form [type=submit]') .wait() .evaluate(function () { return document.querySelector('.username').innerHTML }) .end() .then(function (result) { console.log(result) }) .catch(function (error) { console.error('Search failed:', error); }); } var index = 0; while(index<inputArray.length){ runNext(inputArray[index]); index++; } 

出于某种原因,在命令提示符下执行时,此代码输出以下内容:

 Search failed {} Search failed {} 

我一直在努力去理解为什么这不起作用。 我已经尝试使用这个代码(没有while循环)只运行一次特定的职位,使用runNext(inputArray[0]) ,这工作正常。 所以,当我尝试添加一个while循环来获取有关多个post的信息,为什么它不工作?

梦魇是asynchronous的。 发生这些错误是因为您一次循环调用runNext三次,而不是等待以前的search完成。

因此,前两个search在开始后立即进行,只有最后一个search有时间完成。

尝试在前一个search结尾处启动下一个search:

 var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); var inputArray = [198, 199, 201]; var index = 0; var runNext = function (i) { nightmare .goto('http://theshitpit.com/goto.php') .insert('form [name=postnum]', inputArray[i]) .click('form [type=submit]') .wait() .evaluate(function () { return document.querySelector('.username').innerHTML }) .then(function (result) { console.log(result); }) .then(function(){ index++; // We will only run bext search when we successfully got here if(index < inputArray.length){ runNext(index); } else { console.log("End"); nightmare.halt(); } }) .catch(function (error) { console.error('Search failed:', error); }); } runNext(index);