node.js - Nightmare.js 条件浏览

标签 node.js web-scraping nightmare

我正在尝试了解如何使用“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?

最佳答案

因为 Nightmare 是 then 的,你可以从 .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');
  }
});

关于node.js - Nightmare.js 条件浏览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857545/

相关文章:

python - 从网站提取的值创建 .xls 文件

python - BeautifulSoup - lxml 和 html5lib 解析器抓取差异

node.js - .wait() nightmare 和 Puppeteer evaluate 都找不到 ID

javascript - Nightmare.js找不到CSS标签

node.js - 如何将连接用作具有类型的独立对象?

javascript - 如何将连续的 setInterval() 包装在一个永远的循环中?

python - 使用selenium python从不同的html中获取href标签下的链接

javascript - 如何在浏览器范围内设置全局变量.wait(fn)NightmareJS

node.js - 如何将PM2日志写入sumologic?

Javascript .match() 在使用/gi 标志时不起作用