首页 > 解决方案 > 循环遍历 Microdata 以提取 itemprop 和 text 值

问题描述

尝试遍历 HTML+微数据页面以从 Schema.org 获取产品信息。HTML 可能有未知的子代。我将如何对未知的孩子进行多个循环,还是最好使用 find?

所以我想把所有的模式数据放到一个数组中:

  <span itemprop="name">Product Name</span>

所以上面将被保存到一个数组[name: "Product Name"]中。

      function productData(elem) {
    // Get the children
    console.log("elem 1", elem)
    console.log("elem 2", elem[0])

    if (elem[0]) {
      if (elem[0].hasChildNodes()) {
        elem[0].childNodes.forEach(function (item) {
          console.log("item", item)
          console.log("item chilnodes", item.childNodes)
          return productData(item);
        });
      }
    }
  }


  // Get All Products on the page
  const product = document.querySelectorAll('[itemtype="http://schema.org/Product"]');

  productData(product)

标签: javascripthtmlschema.orgmicrodata

解决方案


虽然这个问题缺少一些细节,但遍历树状结构的未知级别的一个强大工具是递归

function processData (product) {
  if(product.length) {
    const productChildrem =  product[0].childNodes;

    // process this node

    productChildrem.forEach(function (child) {
       return processData(child)
    });
}

通过对每个孩子的重复函数调用,您最终将处理所有孩子。


推荐阅读