【问题标题】:node.js Osmosis write results to filenode.js Osmosis 将结果写入文件
【发布时间】:2017-02-07 23:05:32
【问题描述】:

我已经成功抓取了多个具有相同结构的网站。当我打印结果时,它们看起来不错,现在我想将其全部保存到文件中。

问题是只有最后一次抓取的 MyData 对象被保存到文件中。

var osmosis = require('osmosis');
var jsonfile = require('jsonfile')
var sitesToHandle = ['site1', 'site2', 'site3', 'site4']
sitesToHandle.forEach((urlToHandle) => {
osmosis.get(urlToHandle)
.find('.productList')
.set({
  MyData: [
    {
        'ID': 'a.number',
        'Product': 'a.productname',
        'Price': 'a.price',
    } 
  ]
})
.data(function(document) {
  console.log(document);
    var file = 'osmosis.json'
    jsonfile.writeFile(file, document)
  });
});

【问题讨论】:

    标签: javascript node.js web-scraping osmosis


    【解决方案1】:

    每次迭代都在重写文件。

    您必须使用 {flag: 'a'} 将数据附加到现有 JSON 文件:

    jsonfile.writeFile(file, document, {flag: 'a'})
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多