【问题标题】:Save data json from web to json file将数据 json 从 web 保存到 json 文件
【发布时间】:2020-02-11 16:52:37
【问题描述】:

所以我有这样的代码抓取。但是当我保存到 json 文件时这个代码错误

按摩错误 = TypeError:将循环结构转换为 JSON 从具有构造函数“节点”的对象开始 属性 'children' -> 带有构造函数 'Array' 的对象 索引 0 -> 具有构造函数“节点”的对象 属性“父”关闭圆圈 在 JSON.stringify()

const axios = require('axios');
const cheerio = require('cheerio');
var fs = require('fs');
const url = 'https://icons8.com/line-awesome';

axios(url)
 .then(response => {
   const html = response.data;
   const $ = cheerio.load(html)
   const listIcons = $('.icons-group');
   const list = [];

listIcons.each(function () {
  const title = $(this).find('.icons-title').text();
  const icons = [];
  const panjang = $(this).find('.name');
  for (let i = 0; i < panjang.length; i++) {
    icons.push($(panjang[i]).text());
  }
//   console.log(panjang.length);
//   console.log(panjang[0]);
  list.push({
    title,
    icons,
  });
  console.log(list);
 });
  fs.writeFile('nama.json', JSON.stringify(listIcons, null, 4));
})
.catch(console.error);

【问题讨论】:

标签: javascript


【解决方案1】:

每个 HTML 节点都在某个地方相互引用其他 html 节点。就像 A 节点引用它的父节点,然后 A 的父节点引用父节点的父节点。这使它成为循环,所以这就是你的原因。只需使用您需要的字段,例如 title innerText,而不是获取所有节点对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2015-10-04
    • 2022-01-16
    • 2021-05-05
    • 2017-07-23
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多