arrays - 抓取数组的链接,使用 node-horseman 保存到 .json

标签 arrays json node.js

我们正在制作一个简单的脚本来浏览网站的站点地图,并获取所有链接和 href 值,然后将其保存到 .json 列表中,另一个模块可以使用该脚本来截取这些访问页面的屏幕截图。

到目前为止,我们已经可以让抓取列表的函数发挥作用了。当它在控制台中运行时,我们想要放入数组的数据就会显示出来。

在终端中运行时,找不到任何内容,并且未填充数组。

var fs = require('fs');

var Horseman = require('node-horseman');
var horseman = new Horseman();

function findAllUrls(selector) {

  var urls = [];

  // get all the anchors
  $(selector).each(function() {

    // loop through each anchor and get the href value
    var url = {
      title: $(this).text(),
      url: $(this).attr("href")
    };

    // put the href value in a new array
    urls.push(url);
  });

  // finally return the array of all the href value
  console.log("Log all urls from findAllUrls", urls);
  return urls;
};

horseman
  .open(URL goes here)
  .evaluate(findAllUrls, '.sitemap-links a')
  .then(function(urls) {
    console.log(urls);
    // Save the urls to a json file (lookup node 'fs' module)
    fs.writeFile('urls.json', urls, function (err) {
      if (err) throw err;
      console.log('saved to urls.json');
    });
  })
  .close();

运行测试时会跳过某些内容。我有一种感觉,这与 PhantomJS 模拟浏览器有关,而不是保留数组然后通过。

最佳答案

Horseman 是一个基于 Promise 的 API。因此,findAllUrls 必须返回一个 promise 。 .then 期待的是一个 promise ,而不是一个数组。发生的情况是 .then 在 findAllUrls 返回之前运行,因为它不需要任何东西。我建议你阅读 Promise hereThis是另一篇关于 Promise 的优秀文章。最后,this example来自 horseman 文档的内容与您想要做的非常相似。

这样的东西可能适合您想要做的事情(未经测试):

function findAllUrls(selector) {
  return horseman.evaluate(function () {
      var urls = [];

      // get all the anchors
      $(selector).each(function() {

      // loop through each anchor and get the href value
        var url = {
          title: $(this).text(),
          url: $(this).attr("href")
        };

      // put the href value in a new array
        urls.push(url);
      });

      // finally return the array of all the href value
      console.log("Log all urls from findAllUrls", urls);
      return urls;
    });
};

关于arrays - 抓取数组的链接,使用 node-horseman 保存到 .json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250382/

相关文章:

arrays - python中基于嵌套多个条件过滤Json数组(没有根节点名称)

javascript - Node js v5.9.1 和类 'import/export' 语句

javascript - xml2js,属性名称包含连字符

node.js - 如何使用 node.js 将查询字符串参数传递给 Smartsheet API?

arrays - 两个重复的和

php - 通过JSON搜索构建MySQL Insert?

mysql - 将 perl 数组返回给 MATLAB

java - Find ArrayList 方法到 Find Array 方法

json - 如何在 Mandrill 模板中嵌入 Google 架构脚本

javascript - 如何访问 Rails 中 form_tag 的响应?