【问题标题】:Scraping website, can't nest data with similar name抓取网站,不能嵌套同名数据
【发布时间】:2022-01-21 16:05:42
【问题描述】:

我正在循环浏览一些数据,这些数据是从一些网站上抓取的。 目前我正在刮头。

这是数据结构的一个例子

const head = {
    rel_data: [
      {
        rel: "rel",
        items: [
          {
            type: "type",
            sizes: "sizes",
            href: "href"
          }
        ]
      }
    ]
};

每当rel匹配时,我想将数据插入items

$('head link').each(function(index) {
if(head?.rel_data[index]?.rel == rel) {
  head?.rel_data[index]?.items.push({
    type: (type !== undefined) ? type : null,
    sizes: (sizes !== undefined) ? sizes : null,
    href: (href !== undefined) ? href : null
  });
} else {
  head.rel_data.push({
    rel: (rel !== undefined) ? rel : null,
    items: [
      {
        type: (type !== undefined) ? type : null,
        sizes: (sizes !== undefined) ? sizes : null,
        href: (href !== undefined) ? href : null
      }
    ]
  });
}
})

像这样

rel_data: [
  {
    rel: "icon",
    items: [
      {
        type: "type",
        sizes: "sizes",
        href: "href"
      },
      {
        type: "type",
        sizes: "sizes",
        href: "href"
      }
    ]
  },
  {
    rel: "other-rel-type",
    items: [...]
  }
]

但我得到的是这个。

rel_data: [
  {
    rel: "icon",
      items: [
        {
          type: "type",
          sizes: "sizes",
          href: "href"
              }
    ]
  },
  {
    rel: "icon",
      items: [
        {
          type: "type",
          sizes: "sizes",
          href: "href"
      }
    ]
  }
]

如果我写0,而不是index,它适用于第一种类型的rel(例如图标),但不适用于其他类型?

【问题讨论】:

  • 您正在查询 rel_data 数组中 html 元素的索引。所以第二个图标将查询类似 rel_data[1].rel 或 rel_data[999].rel 的内容。相反,您想要做的是有一个循环遍历所有 rel_data 项的第二个循环,或者以不同的结构准备您的数据,然后对其进行转换。

标签: javascript arrays sorting if-statement web-scraping


【解决方案1】:

一个简单的解决方案是将数据存储在临时对象而不是数组中,并使用rel 值作为键。

然后当你完成后使用Object.values(tempObject) 得到最终的数组

这个对象看起来像:

const obj = {
  "icon": {
    rel: "icon",
    items: [{
        type: "type",
        sizes: "sizes",
        href: "href"
      }

    ]
  },

  "other-rel-type": {
    rel: "other-rel-type",
    items: []
  }
}

然后您的循环的简化版本将类似于:

$('head link').each(function(index) {
    const rel = this.rel
    obj[rel] = obj[rel] || { rel, items:[]}

    obj[rel].items.push({type:..., sizes:...})

});

最后:

head.rel_data = Object.values(obj)

【讨论】:

  • 谢谢!这已经困扰我一段时间了
猜你喜欢
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
相关资源
最近更新 更多