循环显示微数据以提取itemprop和文本值

问题描述 投票:0回答:2

尝试遍历HTML + Microdata页面以从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)
javascript html schema.org microdata
2个回答
0
投票

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

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

    // process this node

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

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


0
投票

如果你想要自己的Microdata解析器,那么你可以从这样的东西开始。当然,你需要详细说明。例如,某些属性是arrays等。

function getItem(elem) {
  var item = {
    '@type': elem.getAttribute('itemtype')
  };
  elem.querySelectorAll('[itemprop]')
    .forEach(function(el) {
      var prop = el.getAttribute('itemprop');
      //special cases
      if (el.hasAttribute('itemscope'))
        item[prop] = item[prop] ? [...item[prop], getItem(el)] : getItem(el); //recursion here
      else if (prop == 'url')
        item[prop] = el.getAttribute('href');
      else if (prop == 'image')
        item[prop] = el.getAttribute('src');
      else
        item[prop] = el.innerText;
      });
   return item;
}
var products = [];

document.querySelectorAll('[itemtype*="http://schema.org/Product"]') //*= for multiple types
  .forEach(function(prod) {
    products.push(getItem(prod));
  });
© www.soinside.com 2019 - 2024. All rights reserved.