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

时间:2016-11-16 02:15:14

标签: javascript node.js npm phantomjs nightmare

以下Javascript旨在使用NightmareJS在网站上搜索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循环来获取有关多个帖子的信息时,为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

梦魇是异步的。发生错误的原因是您在一次循环中调用runNext三次 - 而不是等待之前的搜索完成。

所以前两个搜索是在开始后立即进行的,只有最后一个有时间完成。

尝试在上一个搜索结束时启动下一个搜索:

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);