【问题标题】:Nightmare.js conditional browsingNightmare.js 条件浏览
【发布时间】:2016-06-16 11:15:22
【问题描述】:

我试图了解我应该如何使用“if-then”逻辑制作一个 nightmare.js 脚本。例如

var Nightmare = require('nightmare');
var nightmare = Nightmare({
    show: true,
    paths: {
        userData: '/dev/null'
    }
});

nightmare
    .goto('http://www.example.com/')
    .wait('h1')
    .evaluate(function() {
        return document.querySelector('title').innerText;
    })
    // here: go to url1 if title == '123' otherwise to url2
    .end()
    .then(function() {
        console.log('then', arguments);

    }).catch(function() {
        console.log('end', arguments);
    });

如何根据评估结果使此脚本转到不同的 url?

【问题讨论】:

    标签: node.js web-scraping nightmare


    【解决方案1】:

    由于 Nightmare 是 thenable,你可以从 .then() 返回它,像普通的 Promise 一样链接它。

    var Nightmare = require('nightmare');
    var nightmare = Nightmare({
      show: true,
      paths: {
        userData: '/dev/null'
      }
    });
    
    nightmare
      .goto('http://www.example.com/')
      .wait('h1')
      .evaluate(function() {
        return document.querySelector('title')
          .innerText;
      })
      .then(function(title) {
        if (title == 'someTitle') {
          return nightmare.goto('http://www.yahoo.com');
        } else {
          return nightmare.goto('http://w3c.org');
        }
      })
      .then(function() {
        //since nightmare is `then`able, this `.then()` will
        //execute the call chain described and returned in 
        //the previous `.then()`
        return nightmare
          //... other actions...
          .end();
      })
      .then(function() {
        console.log('done');
      })
      .catch(function() {
        console.log('caught', arguments);
      });
    

    如果您想要一个看起来更同步的逻辑,您可能需要考虑将generatorsvoco 一起使用。比如上面用vo改写:

    var Nightmare = require('nightmare');
    var vo = require('vo');
    
    vo(function * () {
      var nightmare = Nightmare({
        show: true,
        paths: {
          userData: '/dev/null'
        }
      });
    
      var title = yield nightmare
        .goto('http://www.example.com/')
        .wait('h1')
        .evaluate(function() {
          return document.querySelector('title')
            .innerText;
        });
    
      if (title == 'someTitle') {
        yield nightmare.goto('http://www.yahoo.com');
      } else {
        yield nightmare.goto('http://w3c.org');
      }
    
      //... other actions...
    
      yield nightmare.end();
    })(function(err) {
      if (err) {
        console.log('caught', err);
      } else {
        console.log('done');
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2018-07-22
      • 2013-12-27
      • 2010-09-06
      相关资源
      最近更新 更多