【问题标题】:Scraping links for array, saving to .json with node-horseman抓取数组的链接,使用 node-horseman 保存到 .json
【发布时间】:2015-10-21 03:22:56
【问题描述】:

我们正在制作一个简单的脚本来浏览网站的站点地图,并获取所有链接和 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 模拟浏览器有关,而不是让数组通过。

【问题讨论】:

    标签: arrays json node.js


    【解决方案1】:

    Horseman 是一个基于 Promise 的 API。因此, findAllUrls 必须返回一个承诺。 .then 期待一个承诺,而不是一个数组。发生的事情是 .then 在 findAllUrls 返回之前运行,因为它不期望任何东西。我建议你阅读 Promise hereThis 是另一篇关于 Promise 的优秀文章。最后,骑手文档中的this example 与您尝试做的非常相似。

    这样的事情可能适用于您正在尝试做的事情(未经测试):

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

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题。它只是意味着在你的评估函数中的某个地方,骑手遇到了一个错误(但根据经验,它没有显示它是什么错误)。如果遇到错误会自动返回null。

      解决方法是逐行仔细检查你的评估函数,哪一个会产生错误,这可能很困难,因为 horseman 没有指出哪一行有问题。

      旁注,评估函数有多种返回值的选项:回调、承诺和实际值。因此,可以立即返回值,无需承诺,如文档中所述。

      【讨论】:

        猜你喜欢
        • 2017-09-16
        • 1970-01-01
        • 2015-10-12
        • 2021-04-29
        • 2020-02-24
        • 2020-01-21
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        相关资源
        最近更新 更多